2012-04-18 58 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