Piero
Piero

Reputation: 9273

Create only root element in xml doesn't work in java

i'm trying to create an xml file, and create only the root node in which after i add some element, this is what i want:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users>
</Users>

but this is what i have:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users/>

and this is my code:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document doc = documentBuilder.newDocument();
                Element root_users = doc.createElement("Users");
                doc.appendChild(root_users);

                DOMSource source = new DOMSource(doc);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                StreamResult result = new StreamResult(path+"users.xml");
                transformer.transform(source, result);

i can't understand why doesn't work, i want create only the root element because after i want retrieve that root node with this:

Document document = documentBuilder.parse(pathToWrite+"users.xml");
Element root = document.getDocumentElement();

and append the child inside it, to have at the end this structure:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Users>
  <User>
    <Name>Carl</Name>
  </User>
  <User>
    <Name>Bob</Name>
  </User>
</Users>

how i can do it?

Upvotes: 2

Views: 500

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122364

<Users/>

is shorthand for an empty element, i.e. it means exactly the same as

<Users></Users>

If you add children to this element you will get the output you expect.

Note that <Users/> is not the same as

<Users>
</Users>

as the latter element is not empty - it contains a newline. To create this you would need to add a text node child to the root_users element

Document doc = documentBuilder.newDocument();
Element root_users = doc.createElement("Users");
doc.appendChild(root_users);
root_users.appendChild(doc.createTextNode("\n"));

Upvotes: 2

What you want and what you're getting are functionally the same.

The /> at the end is just a shorthand to represent a closing tag.

Try appending things to it anyway, and see what happens.

Upvotes: 2

Related Questions