Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...