如何使用java xpath xpression从xml读取特定标记值

时间:2015-03-20 11:55:15

标签: java xml xpath tags

下面是我的xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soapenv:Envelope >
   <soapenv:Header/>
   <soapenv:Body>
      <inv:GetInvoiceAuthenticationResponse>
         <inv:Header>

            <inv:Cuit>123</inv:Cuit>

            <inv:EmissionPoint>?</inv:EmissionPoint>

            <inv:InvoiceType>?</inv:InvoiceType>

            <inv:ProcessDate>?</inv:ProcessDate>

            <inv:NoOfInvoices>1</inv:NoOfInvoices>

            <inv:Result>?</inv:Result>
         </inv:Header>
         <inv:Invoices>
            <inv:Invoice>
               <inv:Concept>?</inv:Concept>
               <inv:DocumentType>?</inv:DocumentType>
               <inv:DocumentNumber>?</inv:DocumentNumber>
               <inv:InvoiceNumber>?</inv:InvoiceNumber>

               <inv:InvoiceDate>?</inv:InvoiceDate>
               <inv:ResultCode>A</inv:ResultCode>

               <inv:CAE>?</inv:CAE>

               <inv:CAEExpiryDate>?</inv:CAEExpiryDate>


            </inv:Invoice>
         </inv:Invoices>
      </inv:GetInvoiceAuthenticationResponse>
   </soapenv:Body>
</soapenv:Envelope>

我想阅读inv:ResultCode标签。我使用下面的表达但它不起作用。请告诉我我做错了什么?

我应该在xpath.compile中提供哪条路径?

expr = xpath.compile("//inv:Invoices/inv:Invoice/inv:ResultCode/text()");

1 个答案:

答案 0 :(得分:0)

有关Java中可能的方法,请参阅此other SO post,以使用XPath查询命名空间中的元素。个人喜好,因为我不是一个java家伙,我会选择XPath唯一的解决方案using local-name() and namespace-uri()。您的案例的XPath如下:

/*[local-name()='Invoices'
    and namespace-uri()='namespace-uri-for-inv-prefix']
  /*[local-name()='Invoice'
      and namespace-uri()='namespace-uri-for-inv-prefix']
    /*[local-name()='ResultCode'
        and namespace-uri()='namespace-uri-for-inv-prefix']/text()

如果您认为忽略命名空间是安全的,请省略namespace-uri()过滤器以简化(注意上面第2个链接中解释的风险):

/*[local-name()='Invoices']/*[local-name()='Invoice']/*[local-name()='ResultCode']/text()