如何在Android中解析这个XML?
我对 XML 解析很陌生,并且我有自己的解析 XML 的方法。只有该方法适用于只有 1 个子节点的简单 XML 布局。
我现在必须解析一个包含子级的 XML 文件,该文件的子级又包含子级(明白了:)?)
这是我现在拥有的解析方法:
protected Map<String, Maatschappij> getAutopechTel() {
Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(getAssets().open("autopech.xml"));
NodeList nl = doc.getElementsByTagName("dienst");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
Maatschappij maat = new Maatschappij();
maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));
telVoorAutopech.put(maat.getTel(), maat);
}
} catch (Exception e) {
}
return telVoorAutopech;
}
我必须如何调整它才能解析这种类型的 XML 文件:
<Message>
<Service>Serviceeee</Service>
<Owner>Bla</Owner>
<LocationFeedTo>Too</LocationFeedTo>
<Location>http://maps.google.com/?q=52.390001,4.890145</Location>
<Child1>
<Child1_1>
<Child1_1_1>ANWB</Child1_1_1>
</Child1_1>
</Child1>
<Message>
I am quite new to XML parsing and I have my method of parsing XML. Only that method is for simple XML layouts with just 1 child node.
I now have to parse an XML file with childs that have childs that have childs (got it :)?)
This is the parse-method I have now:
protected Map<String, Maatschappij> getAutopechTel() {
Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(getAssets().open("autopech.xml"));
NodeList nl = doc.getElementsByTagName("dienst");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
Maatschappij maat = new Maatschappij();
maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));
telVoorAutopech.put(maat.getTel(), maat);
}
} catch (Exception e) {
}
return telVoorAutopech;
}
How must I adjust this in order to parse this type of XML file:
<Message>
<Service>Serviceeee</Service>
<Owner>Bla</Owner>
<LocationFeedTo>Too</LocationFeedTo>
<Location>http://maps.google.com/?q=52.390001,4.890145</Location>
<Child1>
<Child1_1>
<Child1_1_1>ANWB</Child1_1_1>
</Child1_1>
</Child1>
<Message>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
SAXParser
在Android中解析XML:
这里有详细的教程示例 和 还有 IBMdeveloperWorks 的另一个示例 。
尝试一下这个,但我还没有测试过这段代码。它递归地遍历所有节点并将
ELEMENT_NODE
添加到Vector
中。You can use
SAXParser
to parse XML in Android :Here is a detailed tutorial with example and also another one here by IBM developerWorks.
Try this one out but I haven't tested this code yet. It recursively traverses all the nodes and adds which are
ELEMENT_NODE
to theVector<Node>
.