0

I want to read following XML file:

<RootNode>
    <Node id="1"> value1 </Node>
    <Node id="2"> value2 </Node>
    <Node id="3"> value3 </Node>
    <Node id="4"> value4 </Node>
    <Node1 id="1"> value11 </Node1>
    <Node1 id="2"> value12 </Node2>
    ...
</RootNode>

Now depending on the Node id I want to fetch the value. Like if the Node name is Node and id is 1 the value should be value1 and if Node name is Node1 and id is 2 then value should be value12.

I'm able to get the elements with name Node using this code:

try{
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("Node");
}
catch(Execption e){
    e.printStacktrace();
}

How can I get the elements depending on the attribute(id in this case) ?

Jainendra
  • 24,713
  • 30
  • 122
  • 169

3 Answers3

2

To check the value of id first get attribute 'id' value

private static String getAttributeValue(final Node node, final String attributeName) {
    Element element = (Element) node;
    return element.getAttribute(attributeName);
}


By this way passing node(name = 'node') and attribute name('id') to this method, this will return you the value of attribute id. Now you have the value and you have the node so you can do what ever you want :)

To iterate the node list

for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
}
Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
0

Use this code

for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap parmAttrMap = parmList.item(i).getAttributes();
      if ((parmAttrMap.getNamedItem("id") != null)) {
         //get value of id -- parmAttrMap.getNamedItem("id");
  }
}
Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190
0

XPath could help...

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    Document doc = db.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//Node[@id=\"YOUR_VALUE_HERE\"]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

Replace YOUR_VALUE_HERE for the required id value, and iterate through nl

Cristian Meneses
  • 4,013
  • 17
  • 32