gpt4 book ai didi

Java 变压器空元素

转载 作者:行者123 更新时间:2023-12-02 10:49:42 24 4
gpt4 key购买 nike

我编写了一个程序(我使用的是 JDK 11)来格式化 XML 字符串;但是,我希望我的程序能够收缩空元素。例如:<element></element>应该变成<element/> 。我写了下面的代码,但不起作用:

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
transformer.transform(new DOMSource(unformattedXml),new StreamResult(stringWriter));
return stringWriter.toString();

如何收缩空元素?

最佳答案

我不知道您正在使用哪些 XML 库。我刚刚尝试过原始安装,效果很好。

import java.io.StringReader;
import java.io.StringWriter;
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;
//from w w w. ja va2 s.c om
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Transform {

public static void main(String[] args) throws Exception {
String unformattedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<note>\n"
+ " <to>example</to>\n"
+ " <from>Server</from>\n"
+ " <heading>Reminder</heading>\n"
+ " <body></body>\n"
+ "</note>";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(convertStringToDocument(unformattedXml).getDocumentElement()), new StreamResult(stringWriter));
String s = stringWriter.toString();
System.out.println(s);
}

private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

输出:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>example</to>
<from>Server</from>
<heading>Reminder</heading>
<body/>
</note>

关于Java 变压器空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52270774/

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