解析xml以获取根元素,然后在根标记下动态添加标记

时间:2012-08-28 03:29:51

标签: java dom xml-parsing

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

1 个答案:

答案 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");