给出以下XML(示例):
我需要获取Variant和Version的值.我目前的方法是使用XPath,因为我不能依赖给定的结构.我所知道的是文档中某处有一个元素rsb:Version.
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//Variant";
InputSource inputSource = new InputSource("test.xml");
String result = (String) xpath.evaluate(expression,inputSource,XPathConstants.STRING);
System.out.println(result);
然而,这不输出任何东西.我尝试了以下XPath表达式:
> //变体
> // Variant / text()
> // rsb:Variant
> // rsb:Variant / text()
什么是正确的XPath表达式?或者有更简单的方法来获得这个元素?
最佳答案
我建议只循环遍历文档以查找给定的标记
public static void main(String[] args) throws SAXException,IOException,ParserConfigurationException,TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("test.xml"));
NodeList nodeList = document.getElementsByTagName("rsb:VersionInfo");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
}
}
}
编辑:Yassin指出它不会获得子节点.这应该指出你正确的方向让孩子们.
private static Listteratorterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
原文地址:https://www.jb51.cc/java/437221.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。