Reputation: 30058
I want to write an xml file using the following format:
<root>
<date> 9:51 AM 10/10/2012 </date>
<responseTime> 1.20</responseTime>
<employee>
<name> Mohammad</name>
</employee>
<employee>
<name> Ali</name>
</employee>
<employee>
<name> Mostafa</name>
</employee>
<employee>
<name> Mahmoud</name>
</employee>
</root>
Can I wrote it using DOM? or should I write it by hand?
(The problem in that the employee node is a sequence without a direct parent node to warp all employee elements without date
and responseTime
elements)
Upvotes: 0
Views: 197
Reputation: 9652
I don't see the problem with doing it with DOM.
Code:
public static void main(String[] args) throws ParserConfigurationException, IOException, TransformerException
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("root");
document.appendChild(root);
Element emp1 = document.createElement("employee");
Element emp1name = document.createElement("name");
emp1name.setTextContent("Mohammad");
emp1.appendChild(emp1name);
Element emp2 = document.createElement("employee");
Element emp2name = document.createElement("name");
emp2name.setTextContent("Ali");
emp2.appendChild(emp2name);
root.appendChild(emp1);
root.appendChild(emp2);
printDocument(document, System.out);
}
Output:
<root>
<employee>
<name>Mohammad</name>
</employee>
<employee>
<name>Ali</name>
</employee>
</root>
You can see the source code for printDocument
in this SO Answer.
Full source code can be found here.
Upvotes: 1
Reputation: 141
I think you can write that with DOM (the parent node for "employee" is "root"), however it would be nicer to wrap "employee" nodes with "employees" for example...
Upvotes: 0