Reputation: 313
I have been trying to write something in a XML File, but nothing was written, don't know why. Any help?
This is the code:
Here is the method I use to write on a XML File:
public static void writeXMLFile() throws ParserConfigurationException, FileNotFoundException, IOException
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
/*<Drawer>
* <Shape>
* <type></type>
* <color>
* <x1>
* <y1>
* <x2>
* <y2>
*
*/
Element rootElement = xmlDoc.createElement("Drawing");
Element mainElement= xmlDoc.createElement("Shape");
mainElement.setAttribute("Color", "red");
Text shapesTypeText = xmlDoc.createTextNode("Square");
Element shapeType= xmlDoc.createElement("type");
shapeType.appendChild(shapesTypeText);
mainElement.appendChild(shapeType);
rootElement.appendChild(mainElement);
xmlDoc.adoptNode(rootElement);
OutputFormat outFormat = new OutputFormat(xmlDoc);
outFormat.setIndenting(true);
File xmlFile = new File("saved.xml");
FileOutputStream outStream = new FileOutputStream (xmlFile);
XMLSerializer serializer = new XMLSerializer(outStream,outFormat);
serializer.serialize(xmlDoc);
}
}
Upvotes: 0
Views: 70
Reputation: 12890
Instead of adoptNode, make it as appendChild
public static void main(String[] args) throws ParserConfigurationException, FileNotFoundException, IOException
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
/*<Drawer>
* <Shape>
* <type></type>
* <color>
* <x1>
* <y1>
* <x2>
* <y2>
*
*/
Element rootElement = xmlDoc.createElement("Drawing");
Element mainElement= xmlDoc.createElement("Shape");
mainElement.setAttribute("Color", "red");
Text shapesTypeText = xmlDoc.createTextNode("Square");
Element shapeType= xmlDoc.createElement("type");
shapeType.appendChild(shapesTypeText);
mainElement.appendChild(shapeType);
rootElement.appendChild(mainElement);
**xmlDoc.appendChild(rootElement);**
OutputFormat outFormat = new OutputFormat(xmlDoc);
outFormat.setIndenting(true);
File xmlFile = new File("saved.xml");
FileOutputStream outStream = new FileOutputStream (xmlFile);
XMLSerializer serializer = new XMLSerializer(outStream,outFormat);
serializer.serialize(xmlDoc);
}
adoptNode This attempts to adopt a node from another document to this document.
appendChild This adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.
Upvotes: 2
Reputation: 2297
Please try as follows;
xmlDoc.appendChild(rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("saved.xml"));
transformer.transform(source, result);
Upvotes: 0