如何在android中获取xml的内部内容?

时间:2011-12-29 13:12:46

标签: android xml parsing dom

如何在android中获取xml的内部内容? 例如,如果

我使用了以下代码,但它没有返回实际结果..

String xml ="<hello><hai>welcome<hai></hello>";

InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));           
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();  
Document document = documentBuilder.parse(is);                  
String response = document.getElementsByTagName("hello");   

我需要结果“< hai> welcome< hai>”..提前致谢

1 个答案:

答案 0 :(得分:0)

我有同样的问题,我这样做了:
我做了2个函数,getxml()检查是否有子节点
和xmltagswtf()返回代码的其余部分

public String getxml(Node b){
    String va = "";
    if (b.hasChildNodes()==true){
        int nodes = 0;
        int a=b.getChildNodes().getLength();
        while (nodes <a){
            Node c = b.getChildNodes().item(nodes);
            if(c.getNodeName()!="#text"){
            va+="<"+c.getNodeName()+">"+getxml(c)+"</"+c.getNodeName()+">";
            }else{
                va+=getxml(c);
            }nodes+=1;
        }
    }else{va=b.getTextContent();}
    return va;

}
public String xmltagswtf(String xmlt, String what) throws SAXException, IOException, ParserConfigurationException{
    InputStream is = new ByteArrayInputStream(xmlt.getBytes("UTF-8"));           
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();  
    Document document = documentBuilder.parse(is);                  
    NodeList response = document.getElementsByTagName(what);  
    Node nod = response.item(0);
    String nodos = "";
    if (nod.hasChildNodes()==true){

        int nodes = 0;
        int a=nod.getChildNodes().getLength();
        while (nodes <a){
            Node c = nod.getChildNodes().item(nodes);
            nodos+="<"+c.getNodeName()+">"+getxml(c)+"</"+c.getNodeName()+">";
            nodes+=1;
        }
    }else{
        nodos+=nod.getTextContent();
        System.out.println(nodos);
    }
    return nodos;
}

然后做这样的事情:

String xml ="<hello><hai>welcome</hai></hello>";
String hai =xmltagswtf(xml, "hello");