如何使用dom解析器java在xml中解析相同的名称标签? [英] How to parse same name tag in xml using dom parser java?
本文介绍了如何使用dom解析器java在xml中解析相同的名称标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用dom解析器java解析xml中的相同名称标记?
How do you parse the same name tag in xml using dom parser java?
我有以下xml文件,我想使用dom解析器解析java。
I have the following xml file that I would like to parse using the dom parser in java.
<?xml version="1.0"?>
<GameWorld>
<player>
<playerID>1</playerID>
<inventory>
<item>cards</item>
<item>notes</item>
<item>dice</item>
</inventory>
<position>50 50 10 60</position>
<room>offices</room>
</player>
<player>
<playerID>2</playerID>
<inventory>
<item>notes</item>
<item>dice</item>
<item>cards</item>
</inventory>
<position>10 10 10</position>
<room>security room</room>
</player>
</GameWorld>
推荐答案
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Element root = doc.getDocumentElement();
NodeList nodeList = doc.getElementsByTagName("player");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
// do your stuff
}
但我宁愿建议使用XPath
but I'd rather suggest to use XPath
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GameWorld/player");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
这篇关于如何使用dom解析器java在xml中解析相同的名称标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文