【发布时间】:2012-10-19 01:27:09
【问题描述】:
我在用 Java 解析 XML 文件时遇到了一些问题。该文件采用以下形式:
<root>
<thing>
<name>Thing1</name>
<property>
<name>Property1</name>
</property>
...
</thing>
...
</root>
最终,我想将此文件转换为一个 Thing 对象列表,其中包含一个字符串名称 (Thing1) 和一个 Property 对象列表,每个对象也都有一个名称 (Property1)。
我一直在尝试使用 xpaths 来获取这些数据,但是当我尝试只获取 'thing' 的名称时,它会给出出现在 'thing' 中的所有名称,包括 '财产的。我的代码是:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(filename);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression thingExpr = xpath.compile("//thing");
NodeList things = (NodeList)thingExpr.evaluate(dom, XPathConstants.NODESET);
for(int count = 0; count < things.getLength(); count++)
{
Element thing = (Element)things.item(count);
XPathExpression nameExpr = xpath.compile(".//name/text()");
NodeList name = (NodeList) nameExpr.evaluate(thing, XPathConstants.NODESET);
for(int i = 0; i < name.getLength(); i++)
{
System.out.println(name.item(i).getNodeValue());
}
}
有人可以帮忙吗?提前致谢!
【问题讨论】:
-
您似乎没有准确地表达您想要使用 XPath 生成的内容——即使考虑了 cmets。 Xpath 用于选择我们感兴趣的一些特定节点——在您的特定情况下它们是哪些?您想从这些特定节点中提取哪些数据?请编辑问题并指定此缺失的重要信息。