gpt4 book ai didi

java - 如何在 XML 中创建新元素?

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

我尝试这段代码:

public static void sendXml(String result, int operationN) throws ParserConfigurationException, SAXException, IOException{
String filepath = "journal.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
doc.getFirstChild();
doc.getElementsByTagName("command").item(0);
Element res = doc.createElement("result");
res.setTextContent(result);
doc.appendChild(res);
}

我确信 journal.xmlresult 一切正常。我有异常 HIERARCHY_REQUEST_ERR:尝试插入 org.apache.xerces.dom.CoreDocumentImpl.insertBefore(未知来源)不允许的节点
在 org.apache.xerces.dom.NodeImpl.appendChild(来源未知)
。我做错了什么?

我有这样的结构:

 <?xml version="1.0"?>
<config>
<command> Check title (Total posts,Total topics,Total members,Our newest member)
// here i need result
</command>
<command> Check login
</command>
</config>

最佳答案

你可以这样做

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class WriteXMLFile {

public static void sendXml(String result, int operationN) throws Exception, IOException{
String filepath = "file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);

Node tonode=doc.getElementsByTagName("command").item(0);
Element res = doc.createElement("result");
res.setTextContent(result);
tonode.appendChild(res);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result1 = new StreamResult(new File("file2.xml"));

// Output to console for testing
StreamResult result3 = new StreamResult(System.out);

transformer.transform(source, result1);

System.out.println("File saved!");
}

public static void main(String argv[]) {

try {
WriteXMLFile writeXMLFile=new WriteXMLFile();
writeXMLFile.sendXml("hitest", 1);

} catch (Exception pce) {
pce.printStackTrace();
}
}
}

文件2.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config>
<command>
Check title (Total posts,Total topics,Total members,Our newest member)
<result>hitest</result>
</command>
<command> Check login
</command>
</config>

关于java - 如何在 XML 中创建新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22012228/

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