首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从XML文档中获取属性

从XML文档中获取属性
EN

Stack Overflow用户
提问于 2014-08-28 23:04:03
回答 1查看 46关注 0票数 0

我已经在这里寻找解决方案,但是从我的xml文档中获取这个属性仍然有问题。我正在尝试从这里获取"1“:<update-comments total="1">

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

代码语言:javascript
运行
复制
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();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-28 23:13:32

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

代码语言:javascript
运行
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25559330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档