简体   繁体   中英

How to read the particular tag value from xml using java xpath xpression

Below is my 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>

I want to read the inv:ResultCode tag . I am using below expression but it's not working. Please tell what I am doing wrong?

Which path I should give in xpath.compile ?

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

See this other SO post on possible ways, in Java, to query elements in namespace using XPath. Personal preference since I'm not a java guy, I would go with XPath only solution using local-name() and namespace-uri() . The XPath for your case is as follow :

/*[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()

And if you think you're safe to ignore the namespace, omit namespace-uri() filters to simplify (note the risk as explained in the 2nd link above) :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM