Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml parsing problem

Tags:

java

xml

I'm getting some text from an xml file

URL url_Twitter = new URL("http://twitter.com/statuses/user_timelineID_PROVA.rss"); 
HttpURLConnection conn_Twitter =(HttpURLConnection)url_Twitter.openConnection();   

DocumentBuilderFactory documentBF_Twitter = DocumentBuilderFactory.newInstance();            
DocumentBuilder documentB_Twitter = documentBF_Twitter.newDocumentBuilder();    
Document document_Twitter = documentB_Twitter.parse( conn_Twitter.getInputStream());  

in the xml there are some characters like &# 8217; so when I call

document_Twitter.getElementsByTagName("title").item(2).getFirstChild().getNodeValue()

the string are trunked before that kind of characters

The text is in just one tag

  <item>
    <title>SMWRME: Internet per &#8220;Collaborare senza confini&#8221;. Soprattutto alla SMW di Roma, dal 7 all'11 febbraio. Ecco il terzo percorso. http://cot.ag/ewnJ4F</title>
    <description>SMWRME: Internet per &#8220;Collaborare senza confini&#8221;. Soprattutto alla SMW di Roma, dal 7 all'11 febbraio. Ecco il terzo percorso. http://cot.ag/ewnJ4F</description>
    <pubDate>Mon, 27 Dec 2010 20:05:01 +0000</pubDate>
    <guid>http://twitter.com/SMWRME/statuses/19483914259140609</guid>
    <link>http://twitter.com/SMWRME/statuses/19483914259140609</link>
    <twitter:source>&lt;a href=&quot;http://cotweet.com/?utm_source=sp1&quot; rel=&quot;nofollow&quot;&gt;CoTweet&lt;/a&gt;</twitter:source>
    <twitter:place/>
  </item>

I noticed that this behavior does happen just for android application. The same code works fine for a java application. Can someone help me?

like image 512
lex Avatar asked Feb 17 '26 17:02

lex


1 Answers

Can you try document_Twitter.getElementsByTagName("title").item(2).getTextContent() instead? There might actually be multiple text nodes beneath this node, like

- "item" element
  - "title" element
    - text node "SMWRME: Internet per "
    - text node "&#8220;"
    - text node "Collaborare senza confini"
    - text node "&#8221;"

Most SAX parsers would deliver the character content split in multiple parts so I can imagine a DOM parser to do the same. The method getTextContent should return the text content of all sub sub nodes concatenated.

You could also try to call setCoalescing(true) on your DocumentBuilderFactory before creating the DocumentBuilder, the documentation mentions that this affects CDATA sections but it might also change the handling of character entities.

like image 107
Jörn Horstmann Avatar answered Feb 19 '26 10:02

Jörn Horstmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!