Getting element using attribute

前端 未结 3 1275
北海茫月
北海茫月 2020-12-17 05:17

I am parsing Xml using Java, i want to parse element with the help of attribute value.

For example Data

3条回答
  •  执笔经年
    2020-12-17 06:02

    This is java code to get the child node with given attribute name and value. Is this what you are looking for

        public static Element getNodeWithAttribute(Node root, String attrName, String attrValue)
    {
        NodeList nl = root.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n instanceof Element) {
                Element el = (Element) n;
                if (el.getAttribute(attrName).equals(attrValue)) {
                    return el;
                }else{
           el =  getNodeWithAttribute(n, attrName, attrValue); //search recursively
           if(el != null){
            return el;
           }
        }
            }
        }
        return null;
    }
    

提交回复
热议问题