簡體   English   中英

如何從 xml 解析器獲取屬性值 - Android

[英]How to get attribute value from xml parser - Android

示例 xml

<item>
    <title>Lorem ipsum</title>
    <description>
        <![CDATA[ <img src="http://lorem.ipsum.com/lib/sample.jpg" align="left" hspace="5" width="100"/>lorem ipsum dolor sit amet........ ]]> 
    </description>
    <date>....</date>
</item>

如何使用 XMLPullParser 從 img 標簽部分獲取 src 值?

我正在使用本教程來提取文本值。

DocumentBuilderFactory fectory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fectory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(("<data>" + "here get ur description tag:eg. messages.get(i).getDescription()" + "</data>").getBytes("UTF-8"));
Document document = builder.parse(inputStream);
String imageURL = document.getElementsByTagName("img").item(0).getAttributes().getNamedItem("src").getNodeValue();

正如@Selvin 所說, <img>部分不是 XML 本身的正確部分,因為它被隱藏在 CDATA 部分中(順便說一下,這是一個奇怪的 XML)。

您可以做的最簡單的事情是通過第一次解析獲得description節點。 然后,獲取其文本值,並使用第二個解析器對其進行解析,然后讀取屬性。

這只是第一種方法:您必須首先確保:

  • description內容是格式良好的 XML。 如果沒有,這種方法是沒有用的。
  • description包含一個XML 節點。 如果沒有,您必須在第二次解析之前將其包含在一個虛擬根節點中:

    String newXml="<root>"+cdataContent+"</root>";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM