【发布时间】:2025-12-26 08:10:06
【问题描述】:
我有一个这样的 xml:
<root>
<countries>
<country id="98" nom="Espagne"/>
<country id="76" nom="France"/>
</countries>
</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"/>
【问题讨论】:
-
@andrewjames,对不起,它和我想要的不一样
-
啊,抱歉 - 现在我明白了 - 您希望将整个内部 XML 作为字符串。在这个问题中讨论了这一点:Java DOM 中的Get a node's inner XML as String。我希望这确实有帮助!有几个选项 - 但有些不推荐。
-
我已经看过这个例子,输出和我上面写的一样。问题是返回的字符串有标签父国家,我只需要里面的内部XML
-
我已经更新了我的示例。它产生我认为你需要的东西。看看吧!