我想解析xml文件以获取根元素。然后追加在该根标记下添加名为 first-name 的标记。我该怎么做呢 ?这就是我现在一直在做的事情:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Element blobKey_E = document.createElement("first-name");
blobKey_E.appendChild( document.createTextNode( name ) );
// NOW APPEND blobKey_E to the root element
// After getting the root element from the xml in some directory
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml"));
transformer.transform(source, result);
答案 0 :(得分:6)
Element root = document.getDocumentElement();
root.appendChild(document.createElement("first-name"));
将first-name
追加到DOM树的末尾
插入第一个位置有点困难......
Element root = document.getDocumentElement();
if (root.hasChildNodes()) {
Node firstChild = root.getFirstChild();
root.insertBefore(document.createElement("first-name"), firstChild);
} else {
// Append to as per previous example
}
<强>更新强>
Eleement firstName = document.createElement("first-name");
firstName.setTextContent("Henry");