Log in

View Full Version : Need help creating code to write an XML file


Leithal130
Jan 17, 2013, 12:02 PM
I have this code:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class WriteXMLFile {

public static void main(String argv[]) {

try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("English");
doc.appendChild(rootElement);


Element POS = doc.createElement("POS");
rootElement.appendChild(POS);

Element Pronoun = doc.createElement("Pronoun");
POS.appendChild(Pronoun);

Element Word = doc.createElement("Word");
Pronoun.appendChild(Word);

Element Full = doc.createElement("Full");
Full.appendChild(doc.createTextNode("Hello"));
Word.appendChild(Full);
Full.setAttribute("id", "1");



Element L = doc.createElement("L");
L.appendChild(doc.createTextNode("h"));
Full.appendChild(L);
L.setAttribute("id", "1");




TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("H:\\file.xml"));

transformer.transform(source, result);

System.out.println("File saved!");


}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
catch (TransformerException tfe) {
tfe.printStackTrace();
}

}
}

I want this code to be able to write an xml file for me and it does that but now I need to be able to use elements over but with different id's. The goal of this test version would be to use element "L" with different id attributes to hold the different letters in the word Hello. The current output is :

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <English>
- <POS>
- <Pronoun>
- <Word>
- <Full id="1">
Hello
<L id="1">h</L>
</Full>
</Word>
</Pronoun>
</POS>
</English>

The desired ouput would be:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <English>
- <POS>
- <Pronoun>
- <Word>
- <Full id="1">
Hello
<L id="1">h</L>
<L id="2">e</L>
<L id="3">l</L>
<L id="4">l</L>
<L id="5">o</L>
</Full>
</Word>
</Pronoun>
</POS>
</English>