gpt4 book ai didi

java - pretty-print XML 字符串时防止换行

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:55 26 4
gpt4 key购买 nike

我使用以下代码来漂亮地打印 XML 字符串:

private String prettyFormat(String xml) throws TransformerException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String formattedString = null;
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
formattedString = writer.writeToString(document);

} catch (Exception e) {
throw new RuntimeException(e);
}
return formattedString;
}

我遇到的问题是它包裹了长行,因此:

<message code="272" coeMsgName="CCR_I-Credit-Control-Initial" endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true" request="true" retransmit="false">

变成这样:

<message code="272" coeMsgName="CCR_I-Credit-Control-Initial"
endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true"
request="true" retransmit="false">

最佳答案

你不能。至少在使用 LSSerializer 时不会,因为它使用的 XMLSerializer 是私有(private)的,并且 LSSerializer(及其实现 DOMSerializerImpl)没有任何设置 OutputFormat 属性的方法。不过,您可以直接使用 XMLSerializer:

private static String prettyFormat(String xml) throws TransformerException, ParserConfigurationException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String formattedString = null;
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();

// the last parameter sets indenting/pretty-printing to true:
OutputFormat outputFormat = new OutputFormat("WHATEVER", "UTF-8", true);
// line width = 0 means no line wrapping:
outputFormat.setLineWidth(0);
StringWriter sw = new StringWriter();
XML11Serializer writer = new XML11Serializer(sw, outputFormat);
writer.serialize((Element)document);
formattedString = sw.toString();

} catch (Exception e) {
throw new RuntimeException(e);
}
return formattedString;
}

结果:

<message code="272" coeMsgName="CCR_I-Credit-Control-Initial" endtoend="AUTO" error="false" hopbyhop="AUTO" proxiable="true" request="true" retransmit="false">
<test/>
</message>

关于java - pretty-print XML 字符串时防止换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28347767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com