0

Java - I formed this current XML using Java DocumentBuilderFactory.

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

I want the below new nodes to be added to my New XML using Java DocumentBuilderFactory:

<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>

2

1 Answer 1

0

Try 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();
       }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.