简体   繁体   English

如何从 xml 解析器获取属性值 - Android

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

Sample xml示例 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>

how to get src value from img tag section using XMLPullParser?如何使用 XMLPullParser 从 img 标签部分获取 src 值?

i'm using this tutorial to extract text values.我正在使用本教程来提取文本值。

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

As @Selvin tells, the <img> part is not properly a part of the XML itself, because it is escapped within a CDATA section (making this a strange XML, by he way).正如@Selvin 所说, <img>部分不是 XML 本身的正确部分,因为它被隐藏在 CDATA 部分中(顺便说一下,这是一个奇怪的 XML)。

The easiest thing you could do is to get the description node through a first parsing.您可以做的最简单的事情是通过第一次解析获得description节点。 Then, get its text value, and parse it with a second parser , and then read the attributes.然后,获取其文本值,并使用第二个解析器对其进行解析,然后读取属性。

This is just a first approach: You must first ensure:这只是第一种方法:您必须首先确保:

  • That the description content is a well-formed XML. description内容是格式良好的 XML。 If not, this approach is useless.如果没有,这种方法是没有用的。
  • That the description contains just one XML node. description包含一个XML 节点。 If not, you must enclose it within a dummy root node before the second parsing:如果没有,您必须在第二次解析之前将其包含在一个虚拟根节点中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM