Pages

2009-09-28

Parse XML file with Xpath in Java

Parse XML file MyxmlFile.xml with Xpath "/File/Tag[@name='myAttName']/SubTag" and wrtie the result in mySubTagContent:


DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse (new File("MyxmlFile.xml"));


// normalize text representation
doc.getDocumentElement().normalize ();


Node myNode = SelectNode("/File/Tag[@name='myAttName']/SubTag");


if(myNode!=null) String mySubTagContent = myNode.getTextContent());


private Node SelectNode(String path) throws XPathExpressionException {
    Node child; XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();
    child = (Node) (xp.evaluate(path,doc, XPathConstants.NODE));
    return child;
}

That's it!

No comments:

Post a Comment