Parsing, Modifying, and outputting XML Documents with Java
By Pete Freitag
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);
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
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
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
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.
<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="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
thanks.
please tell me how to sort this xml file, if i m updating it on runtime.
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
i want to read (separate) the attributes of xml file without using tagname in java.
please help me.
Thanks.
I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?
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
I am new to xml can anyone send which site and material is good.
Thanks alot for advance
how to modify the data available in the xml file can any body help me which is very important for my project.
Right then if any updates plz send it to my Email id biswa.nilu@gmail.com
thanks in advance
<record>1</record>
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")));
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....
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.
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
Thanks in advance.
That would be of a great help to me ..
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 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?
this program???
<?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>
http://vtd-xml.sf.net
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();
}
}
it really helped me
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
<?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
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
do u have any idea about csv(comma seprated values) file format. if plz let me know.
Can I read some value from my external file (Text etc) in my XML File?
Thank you in advance..
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.
<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.
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) {
}
}
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....
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
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);