开发者

Getting element using attribute

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

For 开发者_如何学运维example <tag1 att="recent">Data</tag1>

In this i want to parse tag1 data using att value. I am new to java and xml. pls guide me.


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


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


It is a old question but you may use HTMLUnit

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜