我一直在尝试在XML文件中写一些东西,但没有写任何东西,不知道为什么。 有什么帮助吗?
这是代码:
以下是我用于在XML文件上编写的方法:
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);
}
}
答案 0 :(得分:2)
而不是adoptNode,将其设为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 强> 这会尝试将另一个文档中的节点采用到此文档中。
<强>的appendChild 强> 这会将节点newChild添加到此节点的子节点列表的末尾。如果newChild已经在树中,则首先将其删除。
答案 1 :(得分:0)
请尝试如下;
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);