Getting an element using an attribute

I am parsing Xml using Java, I want to parse an element using an attribute value.

for instance <tag1 att="recent">Data</tag1>

In this, I want to parse tag1 data using the att value. I am new to java and xml. Pls guide me.

+3
source share
3 answers

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

Here are the following questions:


, . "" SAX (. ).

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: . .:)

+4

java- node . ,

    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;
}
+4

, HTMLUnit

 HtmlAnchor a = (HtmlAnchor)ele;
 url = a.getHrefAttribute();
0

All Articles