Java 将元素转换为不带<;的XML字符串;?xml版本=…>;前缀
我有一个遗留代码,其中包含很多类似的Java 将元素转换为不带<;的XML字符串;?xml版本=…>;前缀,java,xml,Java,Xml,我有一个遗留代码,其中包含很多类似的org.w3c.dom.Element生成 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element exampleElement = doc.createElement("example"); exampleElement.appendChild(... 如何将exampleElement转换为那样的XML字符串?(允许使用
org.w3c.dom.Element
生成
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element exampleElement = doc.createElement("example");
exampleElement.appendChild(...
如何将exampleElement
转换为那样的XML字符串?(允许使用任何其他库)
...
不是那样
<?xml version="1.0" encoding="UTF-8"?>
<example>
...
</example>
...
有一些选项:
虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。
<?xml version="1.0" encoding="UTF-8"?>
<example>
...
</example>
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OMIT_XML_DECLARATION, "yes");
Writer writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();