作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试这段代码:
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.xml
和 result
一切正常。我有异常 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/
我是一名优秀的程序员,十分优秀!