Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用xpath解析java中的XML文档_Java_Xpath - Fatal编程技术网

使用xpath解析java中的XML文档

使用xpath解析java中的XML文档,java,xpath,Java,Xpath,下面是我要解析的xml文档。我需要得到账户的所有余额,然后把它们加在一起得到一个总数。但我不知道该怎么做 <?xml version="1.0"?> <!-- <!DOCTYPE bank SYSTEM "bank.dtd"> --> -<bank> -<account> <number>3</number> <balance>1295.32</bal

下面是我要解析的xml文档。我需要得到账户的所有余额,然后把它们加在一起得到一个总数。但我不知道该怎么做

 <?xml version="1.0"?>
 <!-- <!DOCTYPE bank SYSTEM "bank.dtd"> -->

-<bank>
   -<account>
        <number>3</number>
        <balance>1295.32</balance>
   </account>
  -<account>
        <number>5</number>
        <balance>3504.63</balance>
   </account>
  -<account>
        <number>7</number>
        <balance>872.00</balance>
    </account>
</bank>

-
-
3.
1295.32
-
5.
3504.63
-
7.
872
我有这个代码到目前为止,但无法让它工作,不知道如何去做这件事

public Bank parse(String fileName) throws SAXException, IOException,
        XPathExpressionException {
    File f = new File(fileName);
    Document doc = builder.parse(f);

    // get the bank

    Bank b = new Bank();

    XPathFactory xpfactory = XPathFactory.newInstance();
    XPath path = xpfactory.newXPath();



       int itemCount =    Integer.parseInt(path.evaluate("count(/bank/account/number)",
            doc));


    for (int i = 1; i<= itemCount; i++) {

String balance = path.compile
   ("/bank/account[" + i +  "]/number/balance").evaluate(doc);

   System.out.println(balance);
公共银行解析(字符串文件名)抛出SAXException、IOException、,
XPathExpressionException{
文件f=新文件(文件名);
文档doc=builder.parse(f);
//去银行
银行b=新银行();
XPathFactory xpfactory=XPathFactory.newInstance();
XPath path=xpfactory.newXPath();
int itemCount=Integer.parseInt(path.evaluate(“count(/bank/account/number)”,
(doc),;

对于(inti=1;i而言,读取项目计数的XPath是正确的

您可以通过以下方式获得所有余额元素的总和:

sum(/bank/account/balance)
没有
/bank/account[1]/number/balance
。该表达式返回一个空结果集。如果需要单个余额,请将
/number/balance/
替换为
/balance

String balance = path.compile("/bank/account[" + i + "]/balance").evaluate(doc);
您的Java代码不完整(请至少发布完整的方法)。是否打印每个帐户的余额?您还可以使用一个XPath表达式对所有余额求和:
sum(/bank/account/balance)