I want to move specific xml element to the top of the list.
xml input:
<?xml version="1.0" encoding="UTF-8"?>
<Values>
<Elem Value="1"/>
<Elem Value="2"/>
<Elem Value="3"/>
</Values>
desired result:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Values>
<Elem Value="2"/>
<Elem Value="1"/>
<Elem Value="3"/>
</Values>
This is my code:
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);
}
but the result is not correct:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Values>
<Elem Value="2"/>
<Elem Value="1"/>
<Elem Value="3"/>
</Values>
Why do I get blank line?!