简体   繁体   English

从XML文档获取属性

[英]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. 我在这里查看了解决方案,但是在从xml文档获取此属性时仍然遇到问题。 I am trying to fetch the "1" from this: <update-comments total="1"> 我试图从中获取“ 1”: <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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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