2012-09-05 154 views
1

我正在使用Android,并且需要从URL获取XML并检索一些值。下载是好的,但有些字段可以包含HTML实体(如–)。当我从Node类(org.w3c.dom.Node)中调用方法getNodeValue()时,该值在找到& char时停止,并截断字符串。getNodeValue()截断org.w3c.dom.Node中的属性内容

例如为:

<title>Episode #56 &#8211; Heroes</title> 

当我打电话的getNodeValue()只返回 “情节#56”。

回答

0

,你可以尝试一些这样的事

String str = "<title>Episode #56 &#8211; Heroes</title>"; 
str = str.replaceAll("&", "amp;"); 

然后尝试解析“STR”它应该工作。

这里是pure with dom parser的示例实现。

public static void main(String[] args) throws XPathExpressionException { 
    String str = "<title>Episode #56 &#8211; Heroes</title>"; 
    str = str.replaceAll("&", "amp;"); 
    Document domDoc = null; 
    try { 
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
     ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); 
     domDoc = docBuilder.parse(bis); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    NodeList nlist = domDoc.getElementsByTagName("title"); 
    //System.out.println("child count "+nlist.getLength()); 
    System.out.println("title value = "+nlist.item(0).getTextContent()); 
} 
+0

我试过了,但没有工作:String title = parser.getValue(e,KEY_TITLE); myObj.setTitle(title.replaceAll(“&”,“amp;”)); // 同样的问题。 –

+0

@Rafael它的工作我有一个给定的示例代码,但它没有用dalvic运行时进行测试,但逻辑可以实现对吗? – Sark