2014-08-28 151 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); 
}