How to get a value from a XML with namespace but without prefix in Java?

828 Views Asked by At

well, this is the xml:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<FECompUltimoAutorizadoResponse xmlns="http://ar.gov.afip.dif.FEV1/">
<FECompUltimoAutorizadoResult>
<PtoVta>12</PtoVta>
<CbteTipo>1</CbteTipo>
<CbteNro>1</CbteNro>
</FECompUltimoAutorizadoResult>
</FECompUltimoAutorizadoResponse>
</soap:Body>
</soap:Envelope>

I Want to get CbteNro, but I cant because the FECompUltimoAutorizadoResponse, I tried with this:

Document document = new Builder().build(responseString, "test.xml");
    Nodes nodes = document.query("/soap:Envelope[@xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"]/soap:Body/FECompUltimoAutorizadoResponse[@xmlns=\"http://ar.gov.afip.dif.FEV1/\"]/FECompUltimoAutorizadoResult/CbteNro\n");
    System.out.println(nodes.get(0).getValue());

usin XOM, but it doesn't work, I receive this message:

Exception in thread "main" nu.xom.XPathException: XPath error: XPath expression uses unbound namespace prefix soap

thanks!

1

There are 1 best solutions below

0
On

Thanks to har07, it can be solved like this:

Document document = new Builder().build(responseString, "test.xml");
Element rootElem = document.getRootElement();
XPathContext xc = XPathContext.makeNamespaceContext(rootElem);
xc.addNamespace("fev1", "http://ar.gov.afip.dif.FEV1/");
Nodes matchedNodes = rootElem.query("/soap:Envelope/soap:Body/fev1:FECompUltimoAutorizadoResponse/fev1:FECompUltimoAutorizadoResult/fev1:CbteNro", xc);