How to retrieve node element's value based on attribute name using dom & xml parsing
<ROOT>
<A>
<aa name="xyz">k,l,m </aa>
<aa name="pqr">a,b,h </aa>
<aa name="abc">s,t,r </aa>
...
</A>
<B>
<bb name="t1">r,st,t</bb>
...
</B>
</ROOT>
... Fragment of implementation tried:
NodeList nodeList = <xmlDoc>.getElementsByTagName("aa");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
System.out.println(element.getTextContent());
// ? getNodeValue() // ? how to get by passing attribute name as matching criteria,
// fe : how to get a,b,h
printed for node aa
with attribute name as pqr
For attribute it will be : element.getAttribute("name");
If you want to search by attribute, then
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xpath.compile("//aa[@name='pqr']").evaluate(doc, XPathConstants.NODESET);
//Rest of the code same
*Please change the xpath according to your need. I did not run it myself, but you get the idea.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.