添加了Java XML-独立属性



我正在为我的一个XML解析方法编写一个测试用例。目标是从字符串创建一个org.w3.dom.Document,然后将其转换回字符串,并将其与原始输入进行比较。

我有以下字符串作为输入:

<?xml version="1.0" encoding="ISO-8859-1"?>
<test>
<test-node>${value}</test-node>
<a a1="a1V">
<a2 a2="a2V"/>
<a3 c1="a3V"/>
</a>
<b b1="b1V"/>
<c c1="c1V">
<c2 b1="c2V"/>
</c>
</test>

使用以下方法将其从字符串转换为文档:

public static Document convertStringToXMLDocument(final String xmlString) throws IOException, SAXException {
try {
return BUILDER_FACTORY.newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));
} catch (ParserConfigurationException e) {
LOGGER.error(e.getMessage());
}
return null;
}

为了转换回字符串,我使用以下方法:

public static String convertNodeToString(final Node n) {
final StringWriter writer = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(n), new StreamResult(writer));
return writer.getBuffer().toString();
} catch (TransformerException e) {
LOGGER.error(e.getMessage());
}
return null;
}

当我运行测试用例时,它失败了,原因是:

Expected :<?xml version="1.0" encoding="ISO-8859-1"?><test><test-node>${value}</test-node><a a1="a1V">   <a2 a2="a2V"/>   <a3 c1="a3V"/></a><b b1="b1V"/><c c1="c1V">   <c2 b1="c2V"/></c></test>
Actual   :<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?><test><test-node>${value}</test-node><a a1="a1V">   <a2 a2="a2V"/>   <a3 c1="a3V"/></a><b b1="b1V"/><c c1="c1V">   <c2 b1="c2V"/></c></test>

问题是独立的=";否">

出于某种原因,它添加了standalone=";否";到使我的测试用例失败的标头。现在我知道我可以通过设置document.setXmlStandalone(true);来删除它。

只要我的输入没有指定standalone=",这就解决了这种情况;否";。

我如何才能在任何情况下都不添加或更改它

在文档实例上设置独立标志

doc.setXmlStandalone(true);

调用convertNodeToString()之前

最新更新