gpt4 book ai didi

java - 关于 XML 文件的写入问题

转载 作者:行者123 更新时间:2023-12-02 06:38:47 27 4
gpt4 key购买 nike

我一直在尝试在 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);
}

}

最佳答案

将其设为appendChild,而不是adoptNode

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);
}

采用节点这尝试将另一个文档中的节点采用到此文档中。

追加子项这会将节点 newChild 添加到该节点的子节点列表的末尾。如果 newChild 已经在树中,则首先将其删除。

关于java - 关于 XML 文件的写入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com