August 16, 2005
Parsing, Modifying, and outputting XML Documents with Java
I have been doing a lot of XML parsing, and manipulation in java lately because I'm building a super dynamic configuration editor for XMS. Its going to be pretty cool once its done because you can even configure third party modules with it. Anyways I thought I'd post some a simple example of parsing and modifying XML with java:
Suppose you have the following XML document:
<?xml version="1.0" ?>
<earth>
<country>us</country>
</earth>
First to parse it using a DOM parser, you can use the DocumentBuilderFactory to get the default DOM parser for your JVM:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");
Now you have an object representation of the XML file in a DOM Document object.
Adding an attribute
Suppose you wanted to add an attribute to the earth node:
Node earth = doc.getFirstChild();
NamedNodeMap earthAttributes = earth.getAttributes();
Attr galaxy = doc.createAttribute("galaxy");
galaxy.setValue("milky way");
earthAttributes.setNamedItem(galaxy);
Adding a child tag
Now lets suppose you wanted to add a child node:
Node canada = doc.createElement("country");
canada.setTextContent("ca");
earth.appendChild(canada);
Write the XML document to a string or file
Finally you probably want to write the xml document to a string or to a file, this can be done with a Transformer object, which come from the transformer factory:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
137 people found this page useful, what do you think?
Trackback Address: 445/DB6030F47DA07A9E7532444CD00ED2C0
Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); trans.transform(source, result);
String xmlString = result.getWriter().toString(); System.out.println(xmlString);
Hi i dont understand what is trans in trans.transform(source, result);
that should be transformer.transform() I will update
Thank you..your explenation is perfect
I'm new to xml as well as java. And this piece of code did help a lot. But, I wanted to know that when I tried to add a new child node, it was added & the entire xml file was displayed on the console, but my original xml file remained unaltered. How can I add the new nodes to the original xml file? Also, I am validating the xml file against a schema, so while adding new child nodes, will the validation happen automatically against the schema or do i have to write some code for that as well. Please help!!!
i am having the same problem as the person above, i need to update the actual xml file. Please help!
To modify an XML file already in existance, you'll want to read the file into a buffer, (modifying the particular attribute while doing so), and then print the entire buffer back to the file.
thanks for the explanation...helped a lot
Good piece of code...working & yes with a line modification you can write the changes to the same file
Does this code require some "extra libraries" installed? I'm getting a cannot resolve symbol error and I can't understand why. I'm running java version "1.4.2_05".
Ah, forgot to mention that I'm a newbie and this is my first coding experiment with Java, so excuse me if the question sounds silly.
Thanks.
Can any one tell how to format a xml file through java program.
I want to create a new xml file .How can I create it through java progrm. How can I add tags/element, adding attributes etc into it . Plz help ...its very urgent . Thanks a lot in advance !!!!
I want to create a new xml file .How can I create it through java progrm. How can I add tags/element, adding attributes etc into it . Plz help ...its very urgent . Thanks a lot in advance !!!!
Hi,
Is there way to modify XML file using JAXP, I am able to overwrite the file with the changes need, but would like to have the same file modified(one particular tag) than completely overwriting the XML file.
Thanks , Vijay
I want to read data from a xml file and want to put the data into a table of postgresql database using core Java .Please help me in coding it.
Hi, Your code is very good. But I need some more clarity for adding another node with same node name. You specified some code in this site but it is not adding correctly under the specified node. It is getting added as new node without parent node and I need to get the XML file updated as I add some nodes or attributes in the program. Please help me in this regard.
Thanks Kishore
Is there any way I can use a string "/0" as node name in xml ? when I try to use it the xml parser treats "/" as file separator and my node is not there.
Good Article. Accept my appreciation .
Very Good One. Helped me a lot. Thanks.
Great code! It helped me a lot. I was amazed that the DOM API does not provide this facility out of the box. Also it would be nice if it was possible for updates to the DOM were reflected in the input file automatically. Do you know if this is possible with later versions of the DOM API?
Hi, transformer.setOutputProperty(OutputKeys.INDENT, "yes"); The above line sets the indentation true and every new tag starts in a new line Is there any way that I can selectively indent my XML on a certain tag and not on the other.
Excellent article, took me out of difficulties, thank you.
The above code is EXACTLY how I've been mutating xml files in Java code, but there's a snag.
When you set the indent output property of a transformer to true, and write the xml file, it inserts text nodes to facilitate the new-lines and tabs. Then when you parse, it reads these new-lines and tabs as text nodes. Then if i remove a node that is between two other nodes, and re-write the xml file, the surrounding text nodes are concatenated and we see a big break.
Thusly:
Original xml:
<HeadTag> <Stuff>"First"</Stuff> <Stuff>"Second"</Stuff> <Stuff>"Third"</Stuff> </HeadTag>
then if I parse and remove the Element with name "Stuff" and text content "Second" and then re-write, I see:
<HeadTag> <Stuff>"First"</Stuff> <Stuff>"Third"</Stuff> </HeadTag>
I have confirmed this is what is happening by obtaining a NodeList of all the children of the documentElement and traversing the list printing the node type name and value for each.
Any suggestions?
~Jason
Shoot... I just read my post and the example xml that I wrote came out improperly formatted. Let me rewrite just the xml.
Original:
<HeadTag><p> <br><br><Stuff>"First"</Stuff><p> <br><br><Stuff>"Second"</Stuff><p> <br><br><Stuff>"Third"</Stuff><p> </HeadTag>
After deleting 'Stuff' element with "Second": <HeadTag><p> <br><br><Stuff>"First"</Stuff><p> <p> <br><br><Stuff>"Third"</Stuff><p> </HeadTag>
when I use "DocumentBuilderFactory to get the default DOM parser for your JVM" I get to the XML file - the parse method returns [#document : null] what is the reason ?
Thanks Pete! I was looking for a quick code example on how to output my modified DOM to a file. This was exactly what I needed. Cheers!
Here i had used Dom parser to read an Xml file.Is it that we can update element content or value trough java program. For example: <fontsize>12</fontsize> so here 12 value should change it to 14,16 like that in xml file trough java program.
Right then if any updates plz send it to my Email id muqthadir_ali@yahoo.co.in
<element name="details"> <element name="server"> <model>G2</model> <serial-number>053232a</serial-number> <rom-version>sdfsd, Type 01212</rom-version> </element>
<element name="os"> <type>linux</type> <version>4.0</version> </element> </element>
How do i remove the Element with the name "element" and replace it with the attribute value.
Help me in this regards....
<element name="details"> <element name="server"> <model>G2</model> <serial-number>053232a</serial-number> <rom-version>sdfsd, Type 01212</rom-version> </element> <element name="os"> <type>linux</type> <version>4.0</version> </element> </element>
How do i remove the Element with the name "element" and replace it with the attribute value.
if you have a small example for this ...please provide me
hi, i have found the above script useful, however i want to generate reports from xml files. i want to read specific nodes in xml file and output them to xsl file or any txt file. any ideas on how to go about this? im new to xml parsing but i have worked with java in university so im still novice to the professional world.
Thankx for the help....it worked for me :)
hai ur explanation is nice.it helps everyone to solve problems while creatinfg xml thanks.
Hi, please tell me how to sort this xml file, if i m updating it on runtime.
i want to add particular attribute into the paticular coloumn
hi all, i want to add a new node for under a pariticular node .is the any possibity of adding it through Dom paser?.or i need to go for jdom?
regards tirumala
Hi, i want to read (separate) the attributes of xml file without using tagname in java. please help me. Thanks.
Hi,
Does this code handles reading very large XML files.. say around 1 GB in size? How to read those files? Thanks
http://www.forex.co.ir http://www.meta-fx.com forex ?????
Hi, its very useful to me. I tried to update the xml, last two days but now I did it within a moment. Thanks for your kind help.
Hi,
I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?
thx for the help buddy... urz is the first link wen ne1 doez a google search fr thz query.... gr8 work... thxx :)
I have xml file in absolute path and I am not able to get the output stream to this file.. can any one give some thoughts on this.
How can I add element in such a manner. <?xml version="1.0" ?> <Global> <earth> <country>us</country> </earth>
Sorry! It will be <?xml version="1.0" ?> <Global><earth> <country>us</country> </earth></Global>
hi all, i have prob in inserting data into xml file,retrieving data from xml file,deleting data from xml file,updation of data in xml file through java(jdom). pls help me for my project
Hi, I am new to xml can anyone send which site and material is good. Thanks alot for advance
Hi I want small info, how to modify the data available in the xml file can any body help me which is very important for my project.
the Indentaion works in windows but somehow is not working in linux... where cud i have possiblely gone wrong... plz help...
Here i had used Dom parser to read an Xml file.Is it that we can update element content or value trough java program. For example: <fontsize>12</fontsize> so here 12 value should change it to 14,16 like that in xml file trough java program. Right then if any updates plz send it to my Email id biswa.nilu@gmail.com
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm
please let me know..
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm please let me know..
here is the pgm:
import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; //import javax.xml.parsers.DocumentBuilder; //import javax.xml.parsers.DocumentBuilderFactory;
public class CountNodes { public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); /* DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file);*/ System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); System.out.println("Number of nodes: " + list.getLength()); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } } }
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm please let me know..
here is the pgm:
import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; //import javax.xml.parsers.DocumentBuilder; //import javax.xml.parsers.DocumentBuilderFactory;
public class CountNodes { public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); /* DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file);*/ System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); System.out.println("Number of nodes: " + list.getLength()); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } } }
hi I have wirte xml file using java code but now I want to add or edit data on it like I entered record 1 I want now to stop at record tag then add a new record 2 how may I do that thanks in advance <record>1</record>