【问题标题】:how to get inner content of xml in android?如何在android中获取xml的内部内容?
【发布时间】:2012-01-29 21:34:25
【问题描述】:
如何在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");
我需要结果“welcome”..提前谢谢
【问题讨论】:
标签:
android
xml
parsing
dom
【解决方案1】:
我遇到了同样的问题,我这样做了:
我做了 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");