简体   繁体   中英

Getting attribute from XML document

I've looked on here for solutions, but I am still having problems getting this attribute from my xml document. I am trying to fetch the "1" from this: <update-comments total="1">

Here the code that I am using to fetch the other values without attributes:

DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
doc = dbBuilder.parse(stream);
doc.getDocumentElement().normalize();

NodeList nodes = doc.getElementsByTagName("update");

for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        String update_type = getValue("update-type", element);
        String numLikes = null;
        String submittedUrl = null;
        String comments = null;

        if (update_type.equals("SHAR")) {
            String shar_user = null;
            String timestamp = null;
            String id = null;
            String updateKey = null;
            String numComments = null;

            try {
                shar_user = getValue("first-name", element)
                        + " " + getValue("last-name", element);
                timestamp = getValue("timestamp", element);
                id = getValue("id", element);
                updateKey = getValue("update-key", element);
                profilePictureUrl = getValue("picture-url", element);
                numLikes = getValue("num-likes", element);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

private static String getValue(String tag, Element element) 
{
    NodeList nodes = element.getElementsByTagName(tag).item(0)
            .getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

This function will get an attribute value from an element using the same strategy that you used to find an element. (Note, you solution only works if an element actually exists.)

private static String getAttributeValue(String tag, Element element, String attribute) 
{
    NodeList nodes = element.getElementsByTagName(tag);
    //note: you should actually check the list size before asking for item(0)
    //because you asked for ElementsByTagName(), you can assume that the node is an Element
    Element elem = (Element) nodes.item(0);
    return elem.getAttribute(attribute);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM