gpt4 book ai didi

java - 在 jdk 11 中序列化 xml 文档时,LSSerializer 缺少 xmlns 属性(在 jdk 8 中工作正常)

转载 作者:行者123 更新时间:2023-12-02 14:23:41 25 4
gpt4 key购买 nike

我正在使用“链接如下”的 LSSerializer 在应用程序中序列化 xml 文档,现在我正在从 java 8 迁移到 11,我发现序列化的 xml 文档缺少默认的 xml 命名空间属性(“xmlns”) 。看来 jdk 8 中使用的 LSSerializer 实现已从 jdk 9 开始被替换。新的实现在序列化 DOM 文档时缺少 xmlns 属性(一个错误?)

为了说明这个问题,以下代码在 java 11 中编译和运行时缺少 xml 中的 xmlns 属性(它在 java 8 中工作正常)

import org.w3c.dom.*;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.*;


public class Test {
public static void main(String[] args) {
String xml = "<bio><body xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><p>test</p></body></bio>";
try {
InputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element node = doc.getDocumentElement();

DOMImplementationLS domImplementation = (DOMImplementationLS)doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String output = lsSerializer.writeToString(node);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}

java8 中的输出:

<?xml version="1.0" encoding="UTF-16"?>
<bio><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>test</p></body></bio>

java11 中的输出:

<?xml version="1.0" encoding="UTF-16"?><bio><body xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><p>test</p></body></bio>

我已经通过更改 LSSerializer 对象的不同 DOM 配置属性下面的链接来检查这一点,例如“namespace-declarations”、“discard-default-content”等,但它全部缺少 xmlns 属性案例。

LSSerialize

altering different DOM Configuration properties

最佳答案

我也遇到了同样的问题。我通过将 namespaceAware 设置为 true(默认为 false)来修复此问题。

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);

关于java - 在 jdk 11 中序列化 xml 文档时,LSSerializer 缺少 xmlns 属性(在 jdk 8 中工作正常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861491/

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