Pete Freitag Pete Freitag

Parsing, Modifying, and outputting XML Documents with Java

Updated on November 02, 2021
By Pete Freitag
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);


java xml dom parsing

Parsing, Modifying, and outputting XML Documents with Java was first published on August 16, 2005.


Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).

Comments

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);
by Emine on 09/27/2005 at 11:12:49 AM UTC
that should be transformer.transform() I will update
by Pete Freitag on 09/27/2005 at 11:14:27 AM UTC
Thank you..your explenation is perfect
by sally on 12/12/2005 at 10:37:59 PM UTC
i am having the same problem as the person above, i need to update the actual xml file. Please help!
by Chung Lam on 03/13/2006 at 2:19:46 AM UTC
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
by Vijay on 07/21/2006 at 5:44:04 PM UTC
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.
by Shashi on 08/23/2006 at 4:32:44 AM UTC
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
by Kishore on 09/27/2006 at 5:08:52 AM UTC
Very Good One. Helped me a lot. Thanks.
by Jiju Jacob on 12/08/2006 at 12:12:42 AM UTC
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?
by Dennis Parrott on 01/12/2007 at 6:15:43 AM UTC
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.
by Rishi on 01/29/2007 at 5:55:56 AM UTC
Excellent article, took me out of difficulties, thank you.
by Edwin HincapiƩ on 01/30/2007 at 6:53:03 AM UTC
<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....
by sharan on 07/03/2007 at 3:33:22 AM UTC
<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
by sharan on 07/03/2007 at 4:04:18 AM UTC
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.
by Mocx on 07/03/2007 at 8:49:26 AM UTC
hai ur explanation is nice.it helps everyone to solve problems while creatinfg xml
thanks.
by haritha on 07/09/2007 at 12:22:22 AM UTC
Hi,
please tell me how to sort this xml file, if i m updating it on runtime.
by ajay on 08/08/2007 at 6:53:26 AM UTC
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
by tirumala on 08/29/2007 at 3:51:19 AM UTC
Hi,
i want to read (separate) the attributes of xml file without using tagname in java.
please help me.
Thanks.
by rekhchand malpani on 09/18/2007 at 3:34:11 AM UTC
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.
by Sankar on 10/26/2007 at 2:14:59 AM UTC
Hi,

I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?
by Malcovitch on 11/12/2007 at 8:45:35 AM UTC
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.
by anil on 12/03/2007 at 3:55:59 PM UTC
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
by bhanu on 01/17/2008 at 11:35:43 AM UTC
Hi,
I am new to xml can anyone send which site and material is good.
Thanks alot for advance
by Ganesh on 01/22/2008 at 11:28:58 PM UTC
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.
by prasanna on 01/29/2008 at 11:55:41 PM UTC
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
by biswa on 02/11/2008 at 4:32:21 AM UTC
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>
by Jessica on 03/27/2008 at 3:45:38 PM UTC
This is a great link it really helped me a lot...thanks..
the code which i pasted below is for the beginners and for those who got [#document : null] in the ouput file,even i got the same problem..below is the solution..

thanks for the author of this link..great work..
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class ODOM
{
public static void main(String args[]) throws Exception
{

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("earth.xml");

Node earth = doc.getFirstChild();
NamedNodeMap earthAttributes = earth.getAttributes();
Attr galaxy = doc.createAttribute("galaxy");
galaxy.setValue("milky way");
earthAttributes.setNamedItem(galaxy);

Node canada = doc.createElement("country");
canada.setTextContent("ca");
earth.appendChild(canada);

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, new StreamResult(new

FileOutputStream("copyearth.xml")));
by Ms.Ranjan on 06/01/2008 at 1:58:59 PM UTC
thanks for giving the idea of using transformerfactory.
by Girish Tewari on 07/17/2008 at 4:07:08 AM UTC
very good, but how could i modify value of existing node
by Rajneesh on 10/22/2008 at 1:17:27 AM UTC
Hi,
I am using XMLSpreadsheet and after updating the values, I am not able to open it. But can see in editplus.
It seems of formating issues.
any help plz....
by ranjan on 11/26/2008 at 6:06:53 PM UTC
Hi,

How can i modify a particular tag in an XML document using DOM.

i am a newbie can any one please help me with this.
by Naveen on 01/29/2009 at 5:09:07 AM UTC
Hi suvarna,

can you please let me know how can we modify the value of a particular tag in a XML document. how can it be written in the same XML document.

can you please help me with this by giving a sample code...

That would be of a great help to me ..

Thanks
by Naveen on 02/02/2009 at 12:11:33 PM UTC
can you please let me know how can we modify the value of a particular attribute in a XML document.
Thanks in advance.
That would be of a great help to me ..
by madhavi on 03/16/2009 at 2:14:11 AM UTC
Below is the Example of creating XML file using Java and simple understanding of root and element




import java.io.StringWriter;

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 org.w3c.dom.Document;
import org.w3c.dom.Element;

public class vsktestXML
{
public vsktestXML()
{
try
{

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();

// Setting the ROOT
Element results = doc.createElement("KOKO");
doc.appendChild(results);

//Setting the First ELEMENT
Element row = doc.createElement("ITDEPT");
results.appendChild(row);

//Setting the CHILD 1
String columnName = "SERVER";
String val = "VSKSERVER";
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(val));
row.appendChild(node);

//Setting the CHILD 2
String columnName2 = "PC";
String val2 = "VSKPC";
Element node1 = doc.createElement(columnName2);
node1.appendChild(doc.createTextNode(val2));
row.appendChild(node1);

//Setting the CHILD 3
String columnName3 = "NETWORK";
String val3 = "VSKLAN";
Element node2 = doc.createElement(columnName3);
node2.appendChild(doc.createTextNode(val3));
row.appendChild(node2);



DOMSource domSource = new DOMSource(doc);

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);

System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?> " );

System.out.println(sw.toString());


}
catch (Exception e)
{
e.printStackTrace(System.out);
}


}
}
by Krishnan on 05/26/2009 at 11:26:02 PM UTC
I was using 1.4.x jre to generate XML file, when I use 1.5.x to generate XML file with same code. I am getting additional xmlns="" for the newly added xml element. what is the possible reason and how to avoid this? if i use 1.4.x i dont see the xmlns ="" for the newly added xml element. Any suggestions/solution please.
by Raj on 08/04/2009 at 7:25:19 PM UTC
VTD-XML allows you to modify XML documents incrementally...
by anon_anon on 08/21/2009 at 1:04:23 PM UTC
Hell everyone,

I have a problem. This might be out of the current context. Any ways, can anyone please tell me how to modify the namespace attribute of an already loaded DOM object?
by Srivinayaka P on 09/22/2009 at 7:56:00 AM UTC
Can I get complete set of code for Parsing, Modifying, and outputting XML Documents with Java
this program???
by Surendar on 10/13/2009 at 8:31:18 AM UTC
I need the code for the following set of XML file:

<?xml version="1.0" encoding="UTF-8" ?>
- <Personnel>
- <Employee type="Permanent">
<Name>Seagull</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
- <Employee type="Contract">
<Name>Robin</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
- <Employee type="Permanent">
<Name>Crow</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
<Employee Type="Contract" />
</Personnel>
by Surendar on 10/13/2009 at 8:37:33 AM UTC
the remove xml declaration works in windows but it's not working in linux... is there any way to get this to work?
by kkrizin on 10/20/2009 at 10:18:01 AM UTC
You may want to look at vtd-xml, the latest open source xml parsing/xpath/indexing lib

http://vtd-xml.sf.net
by barriers on 11/17/2009 at 11:51:56 PM UTC
Hello,

How to add to an xml document instead of over writing it:

Any help will be much appreciated...thanks in advance.

I have managed to get my code to write an xml file with data from input fields from a jsp page... Now I actually need to add new entered details on the jsp page to the existing xml file instead of rewriting it everytime My sample code which currently rewrite the xml file is as follow bellow:


public void addContact(String name, String number) {

System.out.println("New Contact's Name and Number are '" + name
+ "' and '" + number + "' respectively.!!!");

//to write...Xml writer code

System.out.println("got here start of write Xml***");

//this method gets called but only rewrites the Xml file
//Really need it to append/add to the Xml file

try {
String filename = getClass().getClassLoader().getResource("contact-db.xml").getPath();
FileOutputStream fos = new FileOutputStream(filename);
fos.write("<?xml version = \"1.0\"?>".getBytes());
String s = "";

s += "<contacts>";
s += "<contact>";
s += "<name>";
s += name;
s += "</name>";
s += "<number>";
s += number;
s += "</number>";
s += "</contact>";
s += "</contacts>";

s += "";



fos.write(s.getBytes("utf-8"));
fos.close();

//check to see this method got called or not?

System.out.println("***got here end of write Xml");

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
by moe on 12/02/2009 at 6:51:08 AM UTC
nice code
it really helped me
by sudha on 02/19/2010 at 7:38:07 AM UTC
Hi,
I need to create new xml files from existing by changing node values.
Can you help me how can i do it.

Thanks in Advance,
Mayur
by Mayur on 02/26/2010 at 5:28:43 AM UTC
I need the code for the following set of XML file:

<?xml version="1.0" encoding="UTF-8" ?> - <Personnel> - <Employee type="Permanent"> <Name>Seagull</Name> <Id>3674</Id> <Age>34</Age> </Employee> - <Employee type="Contract"> <Name>Robin</Name> <Id>3675</Id> <Age>25</Age> </Employee> - <Employee type="Permanent"> <Name>Crow</Name> <Id>3676</Id> <Age>28</Age> </Employee> <Employee Type="Contract" /> </Personnel>

plz send it to siddharthareddy4u@gmail.com
its urgent
by siddharth on 03/14/2010 at 7:39:15 AM UTC
i need the code 2 read attibute values inside a tag.
like
<measValue measObjLdn="BSS:0,BTSM:3,BTS:0">
<measResults>0 0 </measResults>
<suspect>true</suspect>
</measValue>
i need a java code to read measObjLdn
help me if u can
by siddhartha on 03/14/2010 at 7:42:24 AM UTC
thanks Kevin,
do u have any idea about csv(comma seprated values) file format. if plz let me know.
by siddharth on 03/17/2010 at 9:40:13 PM UTC
sir i m working on xml database and i want to edit it time to time but i m facing a problem when i edit this database.
by ashutosh gangrade khalwa on 05/26/2010 at 4:21:34 AM UTC
sir,i need your help in providing interface for reading and writing the xml content in jsp....
by bharat kashyap on 05/28/2010 at 6:43:31 AM UTC
Hey,

Can I read some value from my external file (Text etc) in my XML File?
by Manas on 09/21/2010 at 8:57:16 AM UTC
Hi All, I have some problem to parse whole XML file. When i am parsing the xml file, once parser is getting one error in xml document then it is terminating, but i need parse should continue and collect all the errors in xml file and at the end should return all the list of errors.
Thank you in advance..
by Pradeep Nandi on 12/13/2010 at 5:09:56 AM UTC
Hi, The Way you made the Steps to Explain is Excellent which makes To Understand at all level of programmers. Thank you
by Prasanna Kumar on 12/27/2010 at 4:00:36 AM UTC
Thanks for such an informative post. I hope I did not miss any comment in this thread, so adding following code for generating XML instead of getting result as String:

StreamResult result = new StreamResult("X:\\Path\\of\\File.xml");

It will directly write to this file location.


Secondly, In case you are Marshalling the java to xml through Jaxb, then you can directly make an InputSource object and parse it with DOM code as mentioned in initial post above:

StringWriter strWritObj = new StringWriter();
InputSource inptSrcObj = new InputSource();
marshaller.marshal(Object , strWritObj );

inptSrcObj.setCharacterStream(new StringReader(strWritObj .toString()));


Now parse this inputSource object :

Document doc = docBuilder.parse(inptSrcObj);

Let me know in case you need more information. Or please let me know in case there is a better way to edit an xml produced by JAXB.
by Aman Verma on 02/03/2011 at 4:08:32 AM UTC
I am trying to update an existing XML file with the below content.
<Company>
<Region>
<Employee>
<Name> Harish </Name>
<Age> 26 </Age>
</Employee>
</Region>
</Company>

After updating the content should look like

<Company>
<Region>
<Employee>
<Name> Harish </Name>
<Age> 26 </Age>
</Employee>
<Employee>
<Name> Vinod </Name>
<Age> 29 </Age>
</Employee>
</Region>
</Company>

How can this be done programatically through Java using DOM API's.
by Sanjeev on 09/07/2011 at 4:47:08 AM UTC
I Need to read a pdf from URL and parse it to XML using java. can anyone help to do this process.
by Usha on 09/16/2011 at 2:58:23 AM UTC
Here is an example method that writes the Xml doc object to a file and to the screen:
public static void writeXmlFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);

// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
Result outResult = new StreamResult(System.out);


// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();

xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
xformer.transform(source, result);
xformer.transform(source, outResult);
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
}
by Jim Pratt on 12/30/2011 at 4:19:25 PM UTC
sample java code to dd data to xml file from java program
by hanan on 06/01/2012 at 1:10:49 PM UTC
0 down vote favorite


I have a xml file like below

<documents>
<document>
<document_type>I</document_type>
<acct_number>A1093879600</acct_number>
</document>
<document>
<document_type>I</document_type>
<acct_number>A0350070800</acct_number>
</document>

First of all I have to check <document_type> value If the value equals I or G then I need to read <acct_number> value from XML then I need to connect with database and pull up the baseid associated with that <acct_number> and write that baseid to xml after <acct_number> node.

Any help appreciated...

Thanks in advance....
by venkateshrao on 08/12/2012 at 12:24:12 PM UTC
Best you use JaxB. Create an XML Schema for your XML(tools available on internet)
then create JaxB classes from the schema can be done via "Trang".
Then you can unmarshal your XML to java, get account Id, query db , populate baseid object and then marshal your object back to XML
by Aman on 08/13/2012 at 2:50:49 AM UTC
This is a useful article, but can anyone advise that if the updates to the physical file have to be done by parallel running threads, then show can the integrity of the structure of xml be ensured? Since in the given example, only one thread is updating the file, so things are ok, but in case of multi threaded app what can be done?
by dorothy on 10/22/2012 at 6:43:45 AM UTC