我想将特定的 xml 元素移动到列表的顶部。
xml输入:
<?xml version="1.0" encoding="UTF-8"?>
<Values>
<Elem Value="1"/>
<Elem Value="2"/>
<Elem Value="3"/>
</Values>
期望的结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Values>
<Elem Value="2"/>
<Elem Value="1"/>
<Elem Value="3"/>
</Values>
这是我的代码:
String valueToFind = "2";
File mFile = new File("C:\\xml.xml");
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(mFile);
NodeList nodeList = document.getElementsByTagName("Elem");
Element element = null;
for (int i = 0; i < nodeList.getLength(); i++) {
element = (Element) nodeList.item(i);
String value = element.getAttribute("Value");
if (valueToFind.equals(value))
break;
else
element = null;
}
if (element != null) {
document.getDocumentElement().removeChild(element);
document.getDocumentElement().insertBefore(element, nodeList.item(0));
}
Source source = new DOMSource(document);
Result result = new StreamResult(mFile.getPath());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
}
但结果不正确:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Values>
<Elem Value="2"/>
<Elem Value="1"/>
<Elem Value="3"/>
</Values>
为什么我得到空行?!