简体   繁体   中英

How to get attribute value from xml parser - Android

Sample 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?

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).

The easiest thing you could do is to get the description node through a first parsing. 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. If not, this approach is useless.
  • That the description contains just one XML node. If not, you must enclose it within a dummy root node before the second parsing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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