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 に答える