Parsing, Modifying, and outputting XML Documents with Java

August 16, 2005
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);


280 people found this page useful, what do you think?

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);
that should be transformer.transform() I will update
Thank you..your explenation is perfect
i am having the same problem as the person above, i need to update the actual xml file. Please help!
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
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.
<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.
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.
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, 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?
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.
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.
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
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>
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")));
thanks for giving the idea of using transformerfactory.
very good, but how could i modify value of existing node
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....
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.
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
can you please let me know how can we modify the value of a particular attribute in a XML document.
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 ..
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); } } }
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.
VTD-XML allows you to modify XML documents incrementally...
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?
Can I get complete set of code for Parsing, Modifying, and outputting XML Documents with Java
this program???
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>
the remove xml declaration works in windows but it's not working in linux... is there any way to get this to work?
You may want to look at vtd-xml, the latest open source xml parsing/xpath/indexing lib

http://vtd-xml.sf.net
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();
}


}
nice code
it really helped me
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
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
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
thanks Kevin,
do u have any idea about csv(comma seprated values) file format. if plz let me know.
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.
sir,i need your help in providing interface for reading and writing the xml content in jsp....
Hey,

Can I read some value from my external file (Text etc) in my XML File?
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..
Hi, The Way you made the Steps to Explain is Excellent which makes To Understand at all level of programmers. Thank you
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.
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.
I Need to read a pdf from URL and parse it to XML using java. can anyone help to do this process.
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) {
}
}
sample java code to dd data to xml file from java program
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....
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
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?


foundeo