Trouble parsing an XML file with a compiled XPATH expression?

jworth28

New Member
I was working through a tutorial and ran across an issue that I expected would work. I am hoping someone can help me with this code. I can't get past this. This code I shared below will match if I use the XPATH expression "//*/text()" but it fails to match when I get more specific than that and use "//tag0:G/text()" . Any idea what I am doing wrong? I am just trying to get the 2 "tag0:G" values out of the XML that is also provided below:import java.io.IOException;import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpression;import javax.xml.xpath.XPathExpressionException;import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.xml.sax.SAXException; public class Test1 { public static void main(String[] args) { System.out.println("Test start..."); String myXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soapenv:Body>" + "<tag0:getA xmlns:tag0=\"http://me.ws.ix\">" + "<tag0:B>" + "<tag0:CC>" + "<tag0:CC>" + "<tag0:D>false</tag0:D>" + "<tag0:E>false</tag0:E>" + "<tag0:F xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>" + "<tag0:G>10001</tag0:G>" + "<tag0:H>7744000002</tag0:H>" + "</tag0:CC>" + "<tag0:CC>" + "<tag0:D>false</tag0:D>" + "<tag0:E>false</tag0:E>" + "<tag0:F xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>" + "<tag0:G>20002</tag0:G>" + "<tag0:H>1111122222</tag0:H>" + "</tag0:CC>" + "</tag0:CC>" + "<tag0:I>2012-05-27 23:38:48</tag0:I>" + "</tag0:B>" + "</tag0:getA>" + "</soapenv:Body>" + "</soapenv:Envelope>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = null; NodeList nodes = null; try { doc = factory.newDocumentBuilder().parse( new InputSource( new StringReader( myXML) ) ); XPathExpression expr = XPathFactory.newInstance().newXPath() .compile("//tag0:G/text()"); // this fails, I don't know why nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } System.out.println("Nodes length: " + nodes.getLength() ); for (int i = 0; i < nodes.getLength(); i++) { String val = nodes.item(i).getNodeValue(); System.out.println( "Val: " + val ); } System.out.println("Test end..."); } }
 
Back
Top