Parsing xml name-value fields

371 Views Asked by At

In my xml, I am seraching for speciffic names and want to retrieve their value.

for example i have this field:

<n0:field>
   <n0:name n4:type="n3:string" xmlns:n3="http://www.w3.org/2001/XMLSchema"   xmlns:n4="http://www.w3.org/2001/XMLSchema-instance">LifePolicyID</n0:name> 
   <n0:value n6:type="n5:string" xmlns:n5="http://www.w3.org/2001/XMLSchema" xmlns:n6="http://www.w3.org/2001/XMLSchema-instance">1</n0:value> 
</n0:field>

I try to get the value of the LifePolicyID name.

Is there a way to do it programatticly?

Right now i am usin Xpath like this:

XPathExpression xpe = xpath.compile("//*[name/text()='" + name +"']/value");

Where name is in this case is LifePolicyID. But it dont work.

Any ideas?

1

There are 1 best solutions below

0
On

Your code seems to work for me

String xml = 
    "<n0:field xmlns:n0='http://test/uri'>" +
    "  <n0:name n4:type='n3:string' xmlns:n3='http://www.w3.org/2001/XMLSchema'   xmlns:n4='http://www.w3.org/2001/XMLSchema-instance'>LifePolicyID</n0:name>" +
    "  <n0:value n6:type='n5:string' xmlns:n5='http://www.w3.org/2001/XMLSchema' xmlns:n6='http://www.w3.org/2001/XMLSchema-instance'>1</n0:value>" +
    "</n0:field>";
String name = "LifePolicyID";
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xpe = xpath.compile("//*[name/text()='" + name +"']/value");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
System.out.println(xpe.evaluate(doc));