我正在解析一个xml文档并将其序列化回来。我想尽量保留原来的缩进和换行。我不想漂亮地打印dom。
考虑下面的代码,其中原始文档在 <div>
标记和无缩进。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import java.io.StringReader;
public class Test {
public static void main(String args[]) throws Exception {
String xmlIn = "<html>\n<div>Hello World!</div>\n</html>";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = documentBuilder.parse(new InputSource(new StringReader(xmlIn)));
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer domTransformer = transfac.newTransformer();
domTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
domTransformer.setOutputProperty(OutputKeys.INDENT, "no");
StreamResult result = new StreamResult(System.out);
DOMSource source = new DOMSource(doc);
domTransformer.transform(source, result);
}
}
我们期望看到:
<html>
<div>Hello World!</div>
</html>
但是,java 8正在打印:
<html>
<div>Hello World!</div>
</html>
java 11正在打印:
<html>
<div>Hello World!</div>
</html>
正如你所看到的,他们都增加了一个额外的新行。Java11还增加了缩进。
如何防止添加额外的新行和缩进?
暂无答案!
目前还没有任何答案,快来回答吧!