编程语言
首页 > 编程语言> > 序列化XML子项并在Java中保留名称空间

序列化XML子项并在Java中保留名称空间

作者:互联网

我有一个Document对象,它像这样建模一个XML

<RootNode xmlns="http://a.com/a" xmlns:b="http://b.com/b">
    <Child />
</RootNode>

使用Java DOM,我需要得到< Child>节点并将其序列化为XML,但保留根节点名称空间.这是我目前拥有的,但它没有序列化命名空间:

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,dom,xml-namespaces
来源: https://codeday.me/bug/20190902/1793148.html