2012-09-09 33 views
0
Document doc = getDomElement(response); // getting DOM element 
      NodeList nl = doc.getElementsByTagName(KEY_ITEM); 
      // looping through all item nodes <item> 
      for (int i = 0; i < nl.getLength(); i++) { 
       Element e = (Element) nl.item(i); 
       String name = getValue(e, KEY_NAME); 
       String description = getValue(e, KEY_DESC); 
       Log.e("description:", description); 
      } 

public String getValue(Element item, String str) { 
    NodeList n = item.getElementsByTagName(str); 
    return this.getElementValue(n.item(0)); 
} 

public final String getElementValue(Node elem) { 
    Node child; 
    if (elem != null) { 
     if (elem.hasChildNodes()) { 
      for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { 
       if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.ELEMENT_NODE)) { 
        return child.getNodeValue(); 
       } 
      } 
     } 
    } 
    return ""; 
} 

在上面,響應是一個XML rss提要,並且一個孩子在下面。發生的事情是我能夠獲得標題,發佈,更新。但是當我使用getValue(e,「content」)時,我得到空字符串。我也想獲得作者姓名。Android rss無法解析帶有屬性的XML

<entry> 
    <title>Title1</title> 
    <link rel="alternate" type="text/html" href="http://www.example.com" /> 
    <id>ID</id> 

    <published>2012-09-08T18:45:40Z</published> 
    <updated>2012-09-08T18:43:01Z</updated> 
    <author> 
     <name>Author name</name> 
     <uri>http://www.example.com</uri> 
    </author> 
    <content type="html" xml:lang="en" xml:base="http://www.example.com/"> 
     &lt;p&gt;Test Test</content> 
</entry> 

回答

1

在代碼

public final String getElementValue(Node elem) { 
    Node child; 
    if (elem != null) { 
     if (elem.hasChildNodes()) { 
      for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { 
       if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.ELEMENT_NODE)) { 
        return child.getNodeValue(); 
       } 
      } 
     } 
    } 
    return ""; 
} 

你得到只是從第一個孩子文本節點的文本。內容可以分成多個文本節點。您可能希望從所有子文本節點收集文本。

public final String getElementValue(Node elem) { 
    Node child; 
    StringBuilder sb = new StringBuilder(); 
    if (elem != null) { 
     if (elem.hasChildNodes()) { 
      for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { 
       if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.ELEMENT_NODE)) { 
        sb.append(child.getNodeValue()); 
       } 
      } 
     } 
    } 
    return sb.toString(); 
} 

要獲取作者姓名值,你需要先下臺另一個層次的層次,爲「名稱」標籤嵌套在「作者」標籤內。當遍歷頂級節點來定位「作者」節點,然後獲取其子節點「名稱」時,這將意味着一些特殊處理。