【问题标题】:How to read the particular tag value from xml using java xpath xpression如何使用 java xpath xpression 从 xml 中读取特定的标签值
【发布时间】:2015-03-20 11:55:14
【问题描述】:

下面是我的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()");

【问题讨论】:

  • 它给你一个错误或者它没有给你正确的输出?
  • 它没有给我想要的输出。它不会抛出任何错误
  • @AnubhavJhalani 您期望得到什么以及代码实际输出了什么?顺便说一句,XML 看起来无效,因为没有声明任何前缀(或者它只是整个 XML 的一部分?)。
  • 它是 xml 的一部分。我希望输出中出现“A”,因为您可以看到“A”写在 inv:ResultCode 标记中
  • 还有“代码实际输出了什么”?

标签: java xml xpath tags


【解决方案1】:

请参阅other SO post,了解在 Java 中使用 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() 过滤器以简化(请注意上面第二个链接中解释的风险):

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

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多