Creating an XML file with nested elements in Java

I would like to create XML file in a Java program using nested elements. I have no issues creating XML files, I just can't seem to organize them properly. The output should be like this:


<ns0:MyNS0 xmlns:ns0="www.blahblah.org">
<MyRoot>
      <MyMainChild>
            <MySubChild1>Attribute1</MySubChild1>
            <MySubChild2>Attribute2</MySubChild2>
            <MySubChild3>
<MySubSubChild1>Attribute3</ MySubSubChild1>
                  <MySubSubChild2>Attribute4</ MySubSubChild2>
            </MySubChild3>
      </MyMainChild>
      <MyMainChild2>Attribute5</ MyMainChild2>
      <MyMainChild3>Attribute6</ MyMainChild3>
</MyRoot>
</ns0:MyNS0>


I've attached a sample of the code I'm using to give you an idea of how I am creating my files, (and hopefully to discourage posts of links on simple XML creation that I've already seen :-p.)
I know the code does not produce the above, desired, result...just showing how I'm doing it.
My main issue is that I have been unable to nest the child elements (MySubSub1 and MySubSub2 above.)

TIA
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
				            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
				            Document doc = docBuilder.newDocument();

				            //child	
				            Element root = doc.createElement("ns0:MyNS0");   
				            root.setAttribute("xmlns:ns0","http://www.blahblah.org");
				            doc.appendChild(root); 

				            Element mainChild = doc.createElement("MyMainChild");				            
				            Element childRO = doc.createElement("Attribute1");
				            childRO.appendChild(doc.createTextNode(Utilities.escapeXML(var1)));
				            mainChild.appendChild(childRO);				             
				            root.appendChild(mainChild);
				            
				            Element mainChild2 = doc.createElement("MyMain2");				            
				            Element childRO2 = doc.createElement("fwefwefwe2");
	
				            
				            Element mainChild3 = doc.createElement("dqwdqwdqwdqw3");				            
				            Element childRO3 = doc.createElement("dwqdwdqdww3");
				            childRO3.appendChild(doc.createTextNode(Utilities.escapeXML(var2)));
				            mainChild3.appendChild(childRO3);				             
				            root.appendChild(mainChild3);

				            
				            childRO2.appendChild(doc.createTextNode(Utilities.escapeXML(var3)));
				            root.appendChild(mainChild2);
				            mainChild2.appendChild(childRO2);   			             
				            
				            
				            		            
				            TransformerFactory transfac = TransformerFactory.newInstance();
				            Transformer trans = transfac.newTransformer();
				            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				            trans.setOutputProperty(OutputKeys.INDENT, "yes");
				            StringWriter sw = new StringWriter();
				            StreamResult result = new StreamResult(sw);
				            DOMSource source = new DOMSource(doc);
				            trans.transform(source, result);
				            String xmlString = sw.toString();
				            
				            File f = new File(outputDir + xmlPrefix + STORED_DATE + "_" + var45 + ".xml");
				            FileWriter fw = new FileWriter(f);
				            fw.write(xmlString);
				            fw.close();

Open in new window

Mike MillerSoftware EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:
Sorry, maybe I'm missing something, but why is that an issue: if you added <MySubChild1> to <MyMainChild>
why can't you use the same way to add <MySubSubChild1> to  <MySubChild3> ?
0
Mike MillerSoftware EngineerAuthor Commented:
I've tried but it always produces each as an individual child element instead of one nested inside the other.
0
for_yanCommented:
Can you post the full program,
so that I could try it myself.
And form which library do you use Utilities ?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

for_yanCommented:
Actually does not matter - I can figure out saomething myself
0
for_yanCommented:
I think you can do it to any level - please look at this - is it something which you meant:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;


import javax.swing.text.Utilities;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;

public class CreateXML {

    public static void main(String[] args) {
        try{

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
				            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
				            Document doc = docBuilder.newDocument();

				            //child
				            Element root = doc.createElement("ns0:MyNS0");
				            root.setAttribute("xmlns:ns0","http://www.blahblah.org");
				            doc.appendChild(root);

				            Element mainChild = doc.createElement("MyMainChild");
				            Element childRO = doc.createElement("Attribute1");
				            childRO.appendChild(doc.createTextNode("123"));
				            mainChild.appendChild(childRO);
				            root.appendChild(mainChild);


                            Element subChild = doc.createElement("SubChild");
                              subChild.setAttribute("one","good");
              

              Element subSubChild = doc.createElement("SubSubChild");
                       subSubChild.appendChild(doc.createTextNode("5234"));
                 subChild.appendChild(subSubChild);
                          mainChild.appendChild(subChild);



				            Element mainChild2 = doc.createElement("MyMain2");
				            Element childRO2 = doc.createElement("fwefwefwe2");


				            Element mainChild3 = doc.createElement("dqwdqwdqwdqw3");
				            Element childRO3 = doc.createElement("dwqdwdqdww3");
				            childRO3.appendChild(doc.createTextNode("345"));
				            mainChild3.appendChild(childRO3);
				            root.appendChild(mainChild3);


				            childRO2.appendChild(doc.createTextNode("456"));
				            root.appendChild(mainChild2);
				            mainChild2.appendChild(childRO2);



				            TransformerFactory transfac = TransformerFactory.newInstance();
				            Transformer trans = transfac.newTransformer();
				            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				            trans.setOutputProperty(OutputKeys.INDENT, "yes");
				            StringWriter sw = new StringWriter();
				            StreamResult result = new StreamResult(sw);
				            DOMSource source = new DOMSource(doc);
				            trans.transform(source, result);
				            String xmlString = sw.toString();

				            File f = new File("output.xml");
				            FileWriter fw = new FileWriter(f);
				            fw.write(xmlString);
				            fw.close();
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

}

Open in new window


<ns0:MyNS0 xmlns:ns0="http://www.blahblah.org">
<MyMainChild>
<Attribute1>123</Attribute1>
<SubChild one="good">
<SubSubChild>5234</SubSubChild>
</SubChild>
</MyMainChild>
<dqwdqwdqwdqw3>
<dwqdwdqdww3>345</dwqdwdqdww3>
</dqwdqwdqwdqw3>
<MyMain2>
<fwefwefwe2>456</fwefwefwe2>
</MyMain2>
</ns0:MyNS0>


Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike MillerSoftware EngineerAuthor Commented:
Getting close i think....


<ns0:MyNS0 xmlns:ns0="http://www.blahblah.org">
<MyMainChild>
<Attribute1>123</Attribute1>
<SubChild one="good">
<SubSubChild>5234</SubSubChild>
</SubChild>
<dqwdqwdqwdqw3>
<dwqdwdqdww3>345</dwqdwdqdww3>
</dqwdqwdqwdqw3>
<MyMain2>
<fwefwefwe2>456</fwefwefwe2>
</MyMain2>
</MyMainChild>
</ns0:MyNS0>
0
for_yanCommented:
Yes, it has SubSubChild nested within SubChild - so now just follow your structure.

It is also a little confusing to name text "Attribute" , of couser you can have any text , but in XML sense
attribute is of couser siomething like that <SubChild one="good"> , so "one" is attribute
0
for_yanCommented:

Actually the main point is that you create all elements invoking createElement() method on doc
It is the way how you use appendChild() for them - that is what determines the structure, the number of netsed levels, etc.
0
Mike MillerSoftware EngineerAuthor Commented:
I got it. Thanks!
0
for_yanCommented:
Great!  You are always welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.