我尝试将XML字符串转换为Document,执行一些DOM操作,然后将其转换回字符串。但是我在转换后难以获得名称空间。我想保留与父元素具有相同名称空间的子元素的命名空间。
我正在运行以下简单代码进行测试:
final String test = "<element xmlns:xc=\"urn:myNamespace\">\n"
+ "\t<child xmlns:xc=\"urn:myNamespace\">\n"
+ "\t\t<attribute>value</attribute>\n"
+ "\t</child>\n"
+ "</element>\n";
System.out.println(test);
final DocumentBuilderFactory documentBuilderFactory = mentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
final Document testDoc = documentBuilderFactory
.newDocumentBuilder()
.parse(new ByteArrayInputStream(test.getBytes(StandardCharsets.UTF_8)));
final StringWriter stringWriter = new StringWriter();
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(testDoc), new StreamResult(stringWriter));
System.out.println(stringWriter.toString());
输出结果为:
<element xmlns:xc="urn:myNamespace">
<child xmlns:xc="urn:myNamespace">
<attribute>value</attribute>
</child>
</element>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<element xmlns:xc="urn:myNamespace">
<child>
<attribute>value</attribute>
</child>
</element>
我正在使用Java 7.有没有办法将名称空间保留在子元素中?