Jainendra
Jainendra

Reputation: 25143

Read XML in Java with XML attributes

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) ?

Upvotes: 0

Views: 176

Answers (3)

Cristian Meneses
Cristian Meneses

Reputation: 4041

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

Upvotes: 0

Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

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");
  }
}

Upvotes: 0

Ashish Aggarwal
Ashish Aggarwal

Reputation: 3026

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);
}

Upvotes: 2

Related Questions