2

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?!

kenny
  • 2,000
  • 6
  • 28
  • 38

2 Answers2

0

The original XML file contains text nodes with white space. Your code removes only the Elem node and inserts it at the top of the list, but the text nodes containing the newline remains.

erikxiv
  • 3,965
  • 1
  • 23
  • 22
0

There is no direct property to remove empty nodes or text nodes with white space available in parsers. As parsers are able to parse the XML with/without those nodes. But if you still would like to do it, then as XML specification has attribute xml:space="preserve", but it didn't worked for Java Example. Here is the typical complicated way of doing it in removing those nodes.

Remove nodes and empty lines

Stackoverflow Example

Community
  • 1
  • 1
Phani
  • 5,319
  • 6
  • 35
  • 43