2014-08-28 123 views
0

我在这里看过解决方案,但我仍然有问题从我的xml文档获取该属性。我想从这个取“1”:<update-comments total="1">从XML文档获取属性

在这里,我使用不带属性,以获取其他值码:

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

你能发表一个你正试图解析的类型的示例xml文档吗? – therealrootuser 2014-08-28 23:09:48

+0

@ mattingly890 http://developer.linkedin.com/documents/network-update-types#Sharing_Updates_SHAR_updates ....“更新评论”就在下面is-commentable – user3776241 2014-08-28 23:11:05

回答

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