Java XML-添加了独立属性
我正在为我的一个XML解析方法编写一个测试用例。 目标是从字符串创建org.w3c.dom.Document,然后将其转换回字符串并与原始输入进行比较 我有以下字符串作为输入:Java XML-添加了独立属性,java,xml,Java,Xml,我正在为我的一个XML解析方法编写一个测试用例。 目标是从字符串创建org.w3c.dom.Document,然后将其转换回字符串并与原始输入进行比较 我有以下字符串作为输入: <?xml version="1.0" encoding="ISO-8859-1"?> <test> <test-node>${value}</test-node> <a a1="a1V"&g
<?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>
应为:${value}
实际值:${value}
问题在于单机版=“否”
出于某种原因,它将standalone=“no”添加到未通过测试用例的标题中。
现在我知道我可以通过设置document.setXmlStandalone(true)来删除它代码>
只要我的输入没有指定standalone=“no”,就可以解决这个问题
如何在任何情况下都不添加或更改它?在文档实例上设置独立标志
doc.setXmlStandalone(true);
在调用convertNodeToString()
之前,如果该值以前在字符串中设置为standalone=“否”,那么这不会覆盖该值吗?否,要设置该值,您需要调用transformer.setOutputProperty(OutputKeys.standalone,“yes”)代码>。JavaDOMAPI有点纠结,我已经试过了。与standalone=“否”一起使用。如果字符串中的standalone=“yes”,则会发生这种情况<代码>预期值:
实际值: