pf » Parsing, Modifying, and outputting XML Documents with Java
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);
//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);
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.
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
Thanks Kishore
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
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>
Right then if any updates plz send it to my Email id muqthadir_ali@yahoo.co.in
<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....
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
regards tirumala
Does this code handles reading very large XML files.. say around 1 GB in size? How to read those files? Thanks
I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?
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(); } } }
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(); } } }
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")));
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
NodeList sections = document.getElementsByTagName("sect1"); int numSections = sections.getLength(); for (int i = 0; i < numSections; i++) { Element section = (Element) sections.item(i); // A <sect1>
Node title = section.getFirstChild(); while (title != null && title.getNodeType() != Node.ELEMENT_NODE) title = title.getNextSibling();
if (title != null) System.out.println(title.getFirstChild().getNodeValue()); }
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); }
} }
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Personnel> <Employee type="permanent"> <Name>KRISHNAN</Name> <Id>1005</Id> <Age>37</Age> </Employee> </Personnel>
- ColdFusion 8 FCKeditor Vulnerability
- Ajax Same Origin Policy No More with Firefox 3.5
- Firefox 3.5 Introduces Origin Header, Security Features
- Tips for Secure File Uploads with ColdFusion
- 7 Years And Blog Entry Number 700
- CFCatch Java Exceptions
- Cheat Sheet for SQL Server
- CFML on Google App Engine for Java
RSS
add to del.icio.us
Pete Freitag is a software engineer, and web developer located in











