我有一个Document对象,它像这样建模一个XML:
使用Java DOM,我需要得到< Child>节点并将其序列化为XML,但保留根节点名称空间.这是我目前拥有的,但它没有序列化命名空间:
public static void main(String[] args) throws Exception {
String xml = "";
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);
}
当前输出:
预期产量: