pf » Parsing, Modifying, and outputting XML Documents with Java

Parsing, Modifying, and outputting XML Documents with Java

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
On 09/27/2005 at 11:12:49 AM MDT Emine wrote:
1
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);

On 09/27/2005 at 11:14:27 AM MDT Pete Freitag wrote:
2
that should be transformer.transform() I will update

On 12/12/2005 at 10:37:59 PM MST sally wrote:
3
Thank you..your explenation is perfect

On 01/09/2006 at 4:26:41 AM MST Sweetypie wrote:
4
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!!!

On 03/13/2006 at 2:19:46 AM MST Chung Lam wrote:
5
i am having the same problem as the person above, i need to update the actual xml file. Please help!

On 03/26/2006 at 4:10:24 AM MST John wrote:
6
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.

On 04/07/2006 at 11:13:12 PM MDT satish wrote:
7
thanks for the explanation...helped a lot

On 06/12/2006 at 4:06:24 AM MDT suvarna wrote:
8
Good piece of code...working & yes with a line modification you can write the changes to the same file

On 07/04/2006 at 10:48:37 AM MDT Paolo wrote:
9
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.

On 07/13/2006 at 8:48:58 AM MDT Sweeti wrote:
10
Can any one tell how to format a xml file through java program.

On 07/13/2006 at 8:53:24 AM MDT Anonymous wrote:
11
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 !!!!

On 07/13/2006 at 8:53:50 AM MDT Pooja wrote:
12
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 !!!!

On 07/21/2006 at 5:44:04 PM MDT Vijay wrote:
13
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

On 08/23/2006 at 4:32:44 AM MDT Shashi wrote:
14
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.

On 09/27/2006 at 5:08:52 AM MDT Kishore wrote:
15
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

On 10/18/2006 at 1:18:22 PM MDT Vikas wrote:
16
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.

On 12/01/2006 at 5:09:49 AM MST Deepak wrote:
17
Good Article. Accept my appreciation .

On 12/08/2006 at 12:12:42 AM MST Jiju Jacob wrote:
18
Very Good One. Helped me a lot. Thanks.

On 01/12/2007 at 6:15:43 AM MST Dennis Parrott wrote:
19
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?

On 01/29/2007 at 5:55:56 AM MST Rishi wrote:
20
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.

On 01/30/2007 at 6:53:03 AM MST Edwin HincapiƩ wrote:
21
Excellent article, took me out of difficulties, thank you.

On 03/28/2007 at 2:18:58 PM MST Jason wrote:
22
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

On 03/28/2007 at 2:24:34 PM MST Jason wrote:
23
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>

On 03/29/2007 at 6:04:47 AM MST Ben wrote:
24
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 ?

On 03/29/2007 at 7:21:27 AM MST Chris wrote:
25
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!

On 04/19/2007 at 8:05:26 AM MDT syed muqthadir wrote:
26
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

On 07/03/2007 at 3:33:22 AM MDT sharan wrote:
27
<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....

On 07/03/2007 at 4:04:18 AM MDT sharan wrote:
28
<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

On 07/03/2007 at 8:49:26 AM MDT Mocx wrote:
29
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.

On 07/05/2007 at 4:04:50 AM MDT Amod wrote:
30
Thankx for the help....it worked for me :)

On 07/09/2007 at 12:22:22 AM MDT haritha wrote:
31
hai ur explanation is nice.it helps everyone to solve problems while creatinfg xml thanks.

On 08/08/2007 at 6:53:26 AM MDT ajay wrote:
32
Hi, please tell me how to sort this xml file, if i m updating it on runtime.

On 08/21/2007 at 12:12:20 AM MDT venkat wrote:
33
i want to add particular attribute into the paticular coloumn

On 08/29/2007 at 3:51:19 AM MDT tirumala wrote:
34
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

On 09/18/2007 at 3:34:11 AM MDT rekhchand malpani wrote:
35
Hi, i want to read (separate) the attributes of xml file without using tagname in java. please help me. Thanks.

On 10/03/2007 at 5:49:34 AM MDT Anonymous wrote:
36
Hi,

Does this code handles reading very large XML files.. say around 1 GB in size? How to read those files? Thanks

On 10/10/2007 at 3:20:57 PM MDT ghgj wrote:
37
http://www.forex.co.ir http://www.meta-fx.com forex ?????

On 10/26/2007 at 2:14:59 AM MDT Sankar wrote:
38
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.

On 11/12/2007 at 8:45:35 AM MST Malcovitch wrote:
39
Hi,

I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?

On 12/03/2007 at 10:38:01 AM MST stratoz wrote:
40
thx for the help buddy... urz is the first link wen ne1 doez a google search fr thz query.... gr8 work... thxx :)

On 12/03/2007 at 3:55:59 PM MST anil wrote:
41
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.

On 12/17/2007 at 10:28:30 PM MST Rajiv wrote:
42
How can I add element in such a manner. <?xml version="1.0" ?> <Global> <earth> <country>us</country> </earth>

On 12/17/2007 at 10:31:05 PM MST Rajiv wrote:
43
Sorry! It will be <?xml version="1.0" ?> <Global><earth> <country>us</country> </earth></Global>

On 01/17/2008 at 11:35:43 AM MST bhanu wrote:
44
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

On 01/22/2008 at 11:28:58 PM MST Ganesh wrote:
45
Hi, I am new to xml can anyone send which site and material is good. Thanks alot for advance

On 01/29/2008 at 11:55:41 PM MST prasanna wrote:
46
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.

On 02/11/2008 at 12:23:02 AM MST ravi wrote:
47
the Indentaion works in windows but somehow is not working in linux... where cud i have possiblely gone wrong... plz help...

On 02/11/2008 at 4:32:21 AM MST biswa wrote:
48
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

On 02/15/2008 at 4:47:33 AM MST Anonymous wrote:
49
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..

On 02/15/2008 at 4:50:23 AM MST Anonymous wrote:
50
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(); } } }

On 02/15/2008 at 4:50:33 AM MST Anonymous wrote:
51
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(); } } }

On 03/27/2008 at 3:45:38 PM MST Jessica wrote:
52
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>




  



Spell Checker by Foundeo





Subscribe to my RSS Feed: solosub RSS
Tags