我有这个XML文件:
...
我需要名为“texture”的所有’scene’子元素,但是使用以下代码:
Element rootNode = document.getDocumentElement();
NodeList childNodes = rootNode.getElementsByTagName("texture");
for (int nodeIx = 0; nodeIx < childNodes.getLength(); nodeIx++) {
Node node = childNodes.item(nodeIx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// cool stuff here
}
}
我也得到’节’内的’纹理’元素.
我怎样才能过滤掉这些?或者我怎样才能获得“场景”直接孩子的元素?
解决方法:
您可以使用Xpath执行此操作,请考虑以下从JAXP Specification 1.4获取的示例(我建议您参考此示例):
// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.Document document = builder.parse(new File("/widgets.xml"));
// evaluate the XPath expression against the Document
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget[@name='a']/@quantity";
Double quantity = (Double) xpath.evaluate(expression, document, XPathConstants.NUMBER);
标签:java,dom,xml-parsing
来源: https://codeday.me/bug/20190902/1788273.html