XPath's with String comparisons

G

gfrommer

Hello Everyone,

I've looked through all the help files I can find, and as far as I
know what Im doing is correct. I wrote a simple program that accepts an
XPath from the command line and runs them against a set XML file. All
the XPath's work great except when I compare the value of one tag
against a string, and then it returns nothing.
Check this out:

XML:

<cap>
<a>
<b> test </b>
<c> test2 </c>
</a>
<a>
<b> test3 </b>
</a>
</cap>

--------------------------------------------

public test(String q) {

try { File impFile = new File("test.xml");
DocumentBuilder db =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document impDoc = db.parse(impFile);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.evaluate(q, impDoc,
XPathConstants.NODESET);
printNodes(nl);

} catch(Exception exc) {
exc.printStackTrace(System.out);
}
}

public void printNodes(NodeList nl) {
if(nl == null) { return; }
if(nl.getLength() == 0) { System.out.println("zero"); return; }
for(int i=0; i<nl.getLength(); i++) {
Node n = nl.item(i);
System.out.println(n);

NodeList nl2 = n.getChildNodes();
printNodes(nl2);
}

return;
}

public static void main(String argv[]) {
test t = new test(argv[0]);
}

-----------------------------------------

When I run the program with the xPath query //a[b="test"] it returns
nothing, when it should return the first <a> block. Any ideas? Any
tag I try and check against a string variable like that returns
nothing. When I try attributes @test="string" that works and returns,
just not tag values.

Thanks everyone
 
M

Mike Schilling

Hello Everyone,

I've looked through all the help files I can find, and as far as I
know what Im doing is correct. I wrote a simple program that accepts an
XPath from the command line and runs them against a set XML file. All
the XPath's work great except when I compare the value of one tag
against a string, and then it returns nothing.
Check this out:

XML:

<cap>
<a>
<b> test </b>
<c> test2 </c>
</a>
<a>
<b> test3 </b>
</a>
</cap>

When I run the program with the xPath query //a[b="test"] it returns
nothing, when it should return the first <a> block. Any ideas? Any
tag I try and check against a string variable like that returns
nothing. When I try attributes @test="string" that works and returns,
just not tag values.

Are the extra spaces in

<b> test </b>

in the XML file, or were they added when composing your post? Without them,
your XPath expression is correct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top