我有一个这样的xml:
<root>
<countries>
<country id="98" nom="Espagne"/>
<country id="76" nom="France"/>
</countries>
</root>
我可以用以下内容读取root标记:
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(XmlFile);
System.out.println("Root element :" + doc.getDocumentElement().getnodename());
Node NodeCountries = doc.getElementsByTagName("countries").item(0);
System.out.println(nodeToString(NodeCountries));
private static String nodeToString(Node node) throws Exception{
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DeclARATION,"yes");
t.setOutputProperty(OutputKeys.INDENT,"yes");
t.transform(new DOMSource(node),new StreamResult(sw));
return sw.toString();
}
但是我不能像这样在国家标签内获取所有内容:
<country id="98" nom="Espagne"/>
<country id="76" nom="France"/>