gpt4 book ai didi

Java Transformer 类在转换时重复一些 xml 节点属性

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

我用 Java 创建了这个简单的函数:

public static String prettify(Document xml) {
String resultValue;
StreamResult xmlOutput;

try {
StringWriter stringWriter = new StringWriter();
xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "no");

Source source = new DOMSource(xml);

transformer.transform(source, xmlOutput);
resultValue = xmlOutput.getWriter().toString();
} catch (Exception e) {
resultValue = "";
}
return resultValue;
}

这是一个非常简单的函数,因此我可以获得缩进的 XML。问题是,在这种特定情况下,它复制了文档元素的属性......很奇怪。该案例是一个 XML 文档,其中包含以下 XML:

<?xml version='1.0'?><Document xmlns='urn:iso:std:iso:20022:tech:xsd:pain.008.001.02' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><CstmrDrctDbtInitn><GrpHdr>A</GrpHdr></CstmrDrctDbtInitn></Document>

我得到:

"<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrCdtTrfInitn>
<GrpHdr>
A
</GrpHdr>
</CstmrCdtTrfInitn>

正如您所看到的,两个属性都是重复的!我尝试过使用输出属性,但什么也没有。例如,如果我向 中添加另一个属性,例如“test='whatever'”,则该特定属性不会重复。任何帮助将不胜感激

最佳答案

感谢@fortytwo的支持。我从 http://ftp.cixug.es/apache/xalan/xalan-j/binaries/ 下载了最新版本的 Xalan (2.7.2)并添加了库:

serializer.jar
xalan.jar
xercesImpl.jar
xml-apis.jar

对于我的项目来说,现在一切都按预期进行。

关于Java Transformer 类在转换时重复一些 xml 节点属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679827/

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