9

I have a XML with a structure similar to this:

<category>
   <subCategoryList>
      <category>

      </category>
      <category>
         <!--and so on -->
      </category>
   </subCategoryList>
</category>

I have a Category class that has a subcategory list (List<Category>). I'm trying to parse this XML file with XPath, but I can't get the child categories of a category.

How can I do this with XPath? Is there a better way to do this?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Mg.
  • 1,469
  • 2
  • 16
  • 29

3 Answers3

19

This link has everything you need. In shorts:

 public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = 
    DocumentBuilderFactory.newInstance();
          domFactory.setNamespaceAware(true); 
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("persons.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
       // XPath Query for showing all nodes value
    XPathExpression expr = xpath.compile("//person/*/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
     System.out.println(nodes.item(i).getNodeValue()); 
    }
  }
ripper234
  • 222,824
  • 274
  • 634
  • 905
2

I believe the XPath expression for this would be "//category/subCategoryList/category". If you just want the children of the root category node (assuming it is the document root node), try "/category/subCategoryList/category".

sblundy
  • 60,628
  • 22
  • 121
  • 123
  • yes, but this returns me a list of all the nodes that matches that expression, so all the childs are included ... thanks – Mg. Dec 04 '08 at 14:53
  • What do you mean all the children are included? I think you're leaving out some detail. – sblundy Dec 04 '08 at 14:57
0

This will work for you:

NodeList nodes = (NodeList) xpath.evaluate("//category//subCategoryList/category",
inputSource, XPathConstants.NODESET);

Then you can parse the children of category as you wish.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194