Get child Node of another Node, given node name

前端 未结 4 1256
再見小時候
再見小時候 2021-02-11 15:21

I have an XML like this:


  
    1
    Declaration of Human Rights

        
相关标签:
4条回答
  • 2021-02-11 16:00

    Check if the Node is a Dom Element, cast, and call getElementsByTagName()

    Node doc = docs.item(i);
    if(doc instanceof Element) {
        Element docElement = (Element)doc;
        ...
        cell = doc.getElementsByTagName("aoo").item(0);
    }
    
    0 讨论(0)
  • 2021-02-11 16:01

    If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

    0 讨论(0)
  • 2021-02-11 16:03

    You should read it recursively, some time ago I had the same question and solve with this code:

    public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
        for (int i = 0; i < nl.getLength(); i++) {
            proccessMenuNode(nl.item(i), menubar);
        }
    }
    
    public void proccessMenuNode(Node n, Container parent) {
        if(!n.getNodeName().equals("menu"))
            return;
        Element element = (Element) n;
        String type = element.getAttribute("type");
        String name = element.getAttribute("name");
        if (type.equals("menu")) {
            NodeList nl = element.getChildNodes();
            JMenu menu = new JMenu(name);
    
            for (int i = 0; i < nl.getLength(); i++)
                proccessMenuNode(nl.item(i), menu);
    
            parent.add(menu);
        } else if (type.equals("item")) {
            JMenuItem item = new JMenuItem(name);
            parent.add(item);
        }
    }
    

    Probably you can adapt it for your case.

    0 讨论(0)
  • 2021-02-11 16:06
    //xn=list of parent nodes......                
    foreach (XmlNode xn in xnList)
    {                                           
        foreach (XmlNode child in xn.ChildNodes) 
        {
            if (child.Name.Equals("name")) 
            {
                name = child.InnerText; 
            }
            if (child.Name.Equals("age"))
            {
                age = child.InnerText; 
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题