Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 631
  • Last Modified:

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

0
Mike Miller
Asked:
Mike Miller
  • 7
  • 3
1 Solution
 
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 7
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now