在 Java 中使用 XPath 解析 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/340787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing XML with XPath in Java
提问by Mg.
I have a XML with a structure similar to this:
我有一个结构与此类似的 XML:
<category>
<subCategoryList>
<category>
</category>
<category>
<!--and so on -->
</category>
</subCategoryList>
</category>
I have a Category class that has a subcategory
list (List<Category>
). I'm trying to parse this XML file with XPath, but I can't get the child categories of a category.
我有一个包含subcategory
列表 ( List<Category>
)的 Category 类。我正在尝试使用 XPath 解析此 XML 文件,但无法获取某个类别的子类别。
How can I do this with XPath? Is there a better way to do this?
我怎样才能用 XPath 做到这一点?有一个更好的方法吗?
采纳答案by ripper234
This linkhas everything you need. In shorts:
这个链接有你需要的一切。简而言之:
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//person/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
回答by sblundy
I believe the XPath expression for this would be "//category/subCategoryList/category
". If you just want the children of the root category
node (assuming it is the document root node), try "/category/subCategoryList/category
".
我相信这个 XPath 表达式将是“ //category/subCategoryList/category
”。如果您只想要根节点的子category
节点(假设它是文档根节点),请尝试“ /category/subCategoryList/category
”。
回答by kgiannakakis
This will work for you:
这对你有用:
NodeList nodes = (NodeList) xpath.evaluate("//category//subCategoryList/category",
inputSource, XPathConstants.NODESET);
Then you can parse the children of category as you wish.
然后,您可以根据需要解析类别的子项。