Java 从XML文档获取属性

Java 从XML文档获取属性,java,xml,Java,Xml,我在这里寻找了一些解决方案,但从xml文档中获取该属性仍然存在问题。我正在尝试从以下位置获取“1: 下面是我用来获取其他没有属性的值的代码: DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder(); doc = dbBuilder.parse(stream); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("update

我在这里寻找了一些解决方案,但从xml文档中获取该属性仍然存在问题。我正在尝试从以下位置获取“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();
}
DocumentBuilder dbBuilder=dbFactory.newDocumentBuilder();
doc=dbBuilder.parse(流);
doc.getDocumentElement().normalize();
NodeList nodes=doc.getElementsByTagName(“更新”);
对于(int i=0;i
此函数将使用与查找元素相同的策略从元素中获取属性值。(注意,仅当元素实际存在时,解决方案才有效。)


您能发布一个您试图解析的类型的示例xml文档吗?@mattingly890。。。。下面的“更新注释”是可注释的
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);
}