找到你要的答案

Q:Convert Element to XML string without prefix

Q:无前缀将元素转换为xml字符串

I have a legacy code with a lot of org.w3c.dom.Element generation like that

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element exampleElement = doc.createElement("example");
exampleElement.appendChild(...

How can I convert exampleElement to XML string like that? (Any additional libraries is allowed)

<example>
  ...
</example>

Not that

<?xml version="1.0" encoding="UTF-8"?>
<example>
  ...
</example>

我有很多org.w3c.dom.element代如有遗留代码

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element exampleElement = doc.createElement("example");
exampleElement.appendChild(...

我怎么能把exampleelement XML字符串吗?(任何额外的库是允许的)

<example>
  ...
</example>

不,

<?xml version="1.0" encoding="UTF-8"?>
<example>
  ...
</example>
answer1: 回答1:

There's some options:

  1. Use an XSL Transformer to apply the changes using the directive omit-xml-declaration

    Transformer transformer= TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("omit-xml-declaration", "yes"); transformer.transform(new DOMSource(document), new StreamResult(stream));

  2. Use a string replace process to replace the first line with a regex or using an indexOf("?>")

  3. Depending on the implementation of w3c Document in the JDK used is possible to use some options in DOMConfiguration of the document like canonical-form

    document.getDomConfig().setParameter("canonical-form",true);

有一些选择:

  1. 使用XSL使用指令omit-xml-declaration应用更改

    Transformer transformer= TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("omit-xml-declaration", "yes"); transformer.transform(new DOMSource(document), new StreamResult(stream));

  2. 使用一个字符串替换工艺取代第一个符合正则表达式或使用IndexOf(”?& gt;”)

  3. 根据在JDK使用W3C文档执行可以在文档的规范型domconfiguration使用一些选项

    文件。getdomconfig()。设置参数(“范式”的,真的);

java  xml