如何使用dom解析器java解析xml中的相同名称标签?
我有以下 xml 文件,我想使用 java 中的 dom 解析器来解析该文件。
<?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
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)