I'm having some trouble parsing an XML file in Java. The file takes the form:
<root>
<thing>
<name>Thing1</name>
<property>
<name>Property1</name>
</property>
...
</thing>
...
</root>
Ultimately, I would like to convert this file into a list of Thing objects, which will have a String name (Thing1) and a list of Property objects, which will each also have a name (Property1).
I've been trying to use xpaths to get this data out, but when I try to get just the name for 'thing', it gives me all of the names that appear in 'thing', including those of the 'property's. My code is:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(filename);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression thingExpr = xpath.compile("//thing");
NodeList things = (NodeList)thingExpr.evaluate(dom, XPathConstants.NODESET);
for(int count = 0; count < things.getLength(); count++)
{
Element thing = (Element)things.item(count);
XPathExpression nameExpr = xpath.compile(".//name/text()");
NodeList name = (NodeList) nameExpr.evaluate(thing, XPathConstants.NODESET);
for(int i = 0; i < name.getLength(); i++)
{
System.out.println(name.item(i).getNodeValue());
}
}
Can anyone help? Thanks in advance!