Getting element using attribute

前端 未结 3 1263
北海茫月
北海茫月 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 05:55

    There are ways to do this. You can use either, xPath (example), DOM Document or SAX Parser (example) to retrieve attribute value and tag elements.

    Here's related questions:

    • Grabbing values in XML elements in Java
    • how to retrieve element value of XML using Java?

    This is a workaround to what you requested. I would never suggest that type of "hack", instead, use SAX instead (see example link).

    public static Element getElementByAttributeValue(Node rootElement, String attributeValue) {
    
        if (rootElement != null && rootElement.hasChildNodes()) {
            NodeList nodeList = rootElement.getChildNodes();
    
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node subNode = nodeList.item(i);
    
                if (subNode.hasAttributes()) {
                    NamedNodeMap nnm = subNode.getAttributes();
    
                    for (int j = 0; j < nnm.getLength(); j++) {
                        Node attrNode = nnm.item(j);
    
                        if (attrNode.getNodeType == Node.ATTRIBUTE_NODE) {
                            Attr attribute = (Attr) attrNode;
    
                            if (attributeValue.equals(attribute.getValue()) {
                                return (Element)subNode;
                            } else {
                                return getElementByAttributeValue(subNode, attributeValue);
                            }
                        }
                    }               
                }
            }
        }
    
        return null;
    }
    

    PS: Code comment not provided. It's given as an exercise to the reader. :)

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-17 06:09

    It is a old question but you may use HTMLUnit

     HtmlAnchor a = (HtmlAnchor)ele;
     url = a.getHrefAttribute();
    
    0 讨论(0)
提交回复
热议问题