我有一个 Document
像这样对 XML 进行建模的对象:
<RootNode xmlns="http://a.com/a" xmlns:b="http://b.com/b">
<Child />
</RootNode>
使用 Java DOM,我需要获取 <Child>
节点并将其序列化为 XML,但保留根节点 namespace 。这是我目前拥有的,但它没有序列化命名空间:
public static void main(String[] args) throws Exception {
String xml = "<RootNode xmlns='http://a.com/a' xmlns:b='http://b.com/b'><Child /></RootNode>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
Node childNode = doc.getFirstChild().getFirstChild();
// serialize to string
StringWriter sw = new StringWriter();
DOMSource domSource = new DOMSource(childNode);
StreamResult streamResult = new StreamResult(sw);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.transform(domSource, streamResult);
String serializedXML = sw.toString();
System.out.println(serializedXML);
}
当前输出:
<?xml version="1.0" encoding="UTF-8"?>
<Child/>
预期输出:
<?xml version="1.0" encoding="UTF-8"?>
<Child xmlns='http://a.com/a' xmlns:b='http://b.com/b' />
最佳答案
您需要明确地将您的 DocumentBuilderFactory
设置为命名空间感知:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
关于java - 序列化 XML 子项并在 Java 中保留 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8180479/