简体   繁体   中英

Child Node's attribute value using DOM

I want to get the attribute value of a childnode in a xml file using DOM parser without XPath..Is there any way that I can do that

I have my node structure like this:

<parent type = "xxxxx">
    <child type = "yyyy">
       <grandchild name = "xxxxx" type ="zzzz" />
       <grandchild name = "xxxyx" type ="zzzx" />
      </child>

I want the names of the grand child given the child's type as input

Yes.

  1. First, check whether the node is an Element . If so, cast to it.
  2. Call Element.getAttribute .
  • Is this child node directly under the parent or at a lower level?
  • Is there more than one child node?

One could use something like this:

NodeList childNodes = parent.getChildNodes();

for(int i = 0; i < childNodes.size(); i++) {
   System.out.println(childNodes.item(i)
                                .getAttributes()
                                .getNamedItem("myAttribute")
                                .getNodeValue());
}

This is one way that I have done it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM