簡體   English   中英

使用DocumentBuilderFactory將節點附加到現有xml-Java

[英]Append Node to Existing xml using DocumentBuilderFactory - Java

Java-我使用Java DocumentBuilderFactory形成了當前的XML。

<server>
<excludeList>
    <exclude>.ear</exclude>
    <exclude>.war</exclude>
    <exclude>.tar</exclude>
</excludeList>

我希望使用Java DocumentBuilderFactory將以下新節點添加到我的New XML中:

<server>
<excludeList>
    <exclude>.ear</exclude>
    <exclude>.war</exclude>
    <exclude>.tar</exclude>
    <exclude>.txt</exclude>
    <exclude>apps\third_party\activator</exclude>
    <exclude>apps\temp</exclude>
    <exclude>apps\xender</exclude>
</excludeList>

嘗試dis:

public class Test
{
    public static void main(String argv[]) {

       try {
        String filepath = "c:\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the root element
        Node server = doc.getFirstChild();

        // Get the excludeList element by tag name directly
        Node excludeList = doc.getElementsByTagName("excludeList").item(0);


        // append a new node to excludeList
        Element exclude = doc.createElement("exclude");
        excludeList.appendChild(doc.createTextNode("apps\\temp"));

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM