0

似乎很奇怪,我无法获取节点的值,因为它在 CDATA 中……这是我读过的带有 setCoalescing 的解析器:

public class XMLParser {
public String getXmlFromUrl(String url) {
    String xml = null;
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}
public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 
    } catch (ParserConfigurationException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    }
    // return DOM
    return doc;
}
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
} 
}

和我的代码来获取值:

    // XML
    final String URL = "http://example.com/xml.xml";
    // XML node keys
    final String parente = "dict";
    final String chiave = "key";
    final String stringa = "string";
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml);
    NodeList nl = doc.getElementsByTagName(parente);
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        String chiave_trovata = parser.getValue(e, chiave);
        String stringa_trovata = parser.getValue(e, stringa);
        System.out.println("a"+stringa_trovata);
    }

但我的 stringa_trovata 是空的,因为就像

你能帮助我吗?

4

1 回答 1

1

解决只需评论 if(child.getNodeType() == Node.TEXT_NODE){

于 2012-09-21T09:39:13.067 回答