Search code examples
javaxmlparsingdomjxpath

How to parse XML file with JxPath and DOM parser


I need simple example how can be possible to parse XML files with Java DOM parser and Apache JxPath. I am aware with DOM parser technology, but now I'm trying to integrate JxPath in my source.

I have searched in a network, but I can't find working example.

For test I've got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd gender="male">
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd gender="male">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
</catalog>

Java code:

File file = new File("Files/catalog.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try
{
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(file);

    NodeList nList = doc.getElementsByTagName("cd");
    for(int j = 0; j<nList.getLength(); j++){

        Element element = (Element)nList.item(j);
        System.out.println(element.getElementsByTagName("artist").item(0).getTextContent() + "\n");

    }

}
catch (ParserConfigurationException | SAXException | IOException e)
{
    e.printStackTrace();
}

I have read for classes Container, DocumentContainer and JXPathContext, but I will be grateful for some help or for web source with specific working example.


Solution

  • Here is the example that do similar work as yours.

    File file = new File("Files/catalog.xml");
    DocumentContainer dc = new DocumentContainer(file.toURI().toURL());
    JXPathContext ctx = JXPathContext.newContext(dc);
    Iterator iter = ctx.iterate("//cd/artist");
    //In this case, following API will return DOM object
    //Iterator iter = ctx.selectNodes("//cd/artist").iterator();
    while (iter.hasNext()) {
        System.out.println(iter.next());//object type is String
    }