从XML文档获取属性

时间:2014-08-28 23:04:04

标签: java xml

我在这里寻找解决方案,但是我仍然无法从我的xml文档中获取此属性。我想从这里获取“1”:<update-comments total="1">

这里是我用来获取没有属性的其他值的代码:

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

1 个答案:

答案 0 :(得分:2)

此函数将使用您用于查找元素的相同策略从元素获取属性值。 (注意,您的解决方案仅在元素实际存在时才有效。)

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