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")を使用すると、空の文字列が取得されます。著者名も教えてください。

<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>
4

1 に答える 1

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

「name」タグは「author」タグ内にネストされているため、作成者名の値を取得するには、最初に階層内の別のレベルにステップダウンする必要があります。これは、最上位ノードをトラバースして「作成者」ノードを見つけ、その子「名前」ノードを取得するときに、少し特別な処理を意味します。

于 2012-09-09T13:19:44.753 に答える