2012-04-18 90 views
1

以下是XML文件 -如何从使用Java的XML节点组中获取文本?

<Country> 
    <Group> 
    <C>Tokyo</C> 
    <C>Beijing</C> 
    <C>Bangkok</C> 
    </Group> 
    <Group> 
    <C>New Delhi</C> 
    <C>Mumbai</C> 
    </Group> 
    <Group> 
    <C>Colombo</C> 
    </Group> 
</Country> 

我想城市的名称保存到使用Java & XPath的文本文件 - 下面是Java代码是不能做要紧。

..... 
..... 
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
domFactory.setNamespaceAware(true); 
DocumentBuilder builder = domFactory.newDocumentBuilder(); 
Document doc = builder.parse("Continent.xml"); 
XPath xpath = XPathFactory.newInstance().newXPath(); 
// XPath Query for showing all nodes value 
XPathExpression expr = xpath.compile("//Country/Group"); 
Object result = expr.evaluate(doc, XPathConstants.NODESET); 
NodeList nodes = (NodeList) result; 
BufferedWriter out = new BufferedWriter(new FileWriter("Cities.txt")); 
Node node; 
for (int i = 0; i < nodes.getLength(); i++) 
{ 
    node = nodes.item(i); 
    String city = xpath.evaluate("C",node); 
    out.write(" " + city + "\r\n"); 
} 
out.close(); 
..... 
..... 

有人可以帮助我获得所需的输出吗?

+0

所以你的问题是怎么写的城市到文件? – Rudy 2012-04-18 05:42:05

+0

@Rudy - 是的......只有城市...... – John 2012-04-18 05:50:50

+0

当你说不通时,哪条线会给你带来错误? – Rudy 2012-04-18 05:52:10

回答

1

你只得到第一个城市,因为这就是你要求的。你的第一个XPATH表达式返回所有的Group节点。你迭代这些并评估相对于每个Group的XPATH C,返回一个城市。

只需将第一个XPATH更改为//Country/Group/C并完全消除第二个XPATH - 只需打印第一个XPATH返回的每个节点的文本值即可。

即:

XPathExpression expr = xpath.compile("//Country/Group/C"); 
... 
for (int i = 0; i < nodes.getLength(); i++) 
{ 
    node = nodes.item(i); 
    out.write(" " + node.getTextContent() + "\n"); 
} 
+0

做了什么更改?我没有得到确切的所需输出.. !! – John 2012-04-18 06:50:09

+0

代码工作得很好,输出是根据需要..非常感谢 – John 2012-04-18 07:03:21