5

我想解析 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);
4

1 回答 1

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");
于 2012-08-28T03:34:08.093 回答