以下是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();
.....
.....
有人可以幫助我獲得所需的輸出嗎?
所以你的問題是怎麼寫的城市到文件? – Rudy 2012-04-18 05:42:05
@Rudy - 是的......只有城市...... – John 2012-04-18 05:50:50
當你說不通時,哪條線會給你帶來錯誤? – Rudy 2012-04-18 05:52:10