Java: How to read and write xml files?
-
I have been working in C++ and .Net from last 2 Years. Now i got and opportunity to develop a small application in Java, where i came across a situation to read and write xml file. Since i am new to Java so i was wondering that what is the most easy way to read and write xml file using Java. Any answer with some sample code, or to some good tutorial will be highly appreciated.
-
Answer:
Here is a quick example on how to read and write a simple xml file with its dtd: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE roles SYSTEM "roles.dtd"> <roles> <role1>User</role1> <role2>Author</role2> <role3>Admin</role3> <role4/> </roles> and the dtd: <?xml version="1.0" encoding="UTF-8"?> <!ELEMENT roles (role1,role2,role3,role4)> <!ELEMENT role1 (#PCDATA)> <!ELEMENT role2 (#PCDATA)> <!ELEMENT role3 (#PCDATA)> <!ELEMENT role4 (#PCDATA)> First import these: import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.w3c.dom.*; Here are a few variables you will need: private String role1 = null; private String role2 = null; private String role3 = null; private String role4 = null; private ArrayList<String> rolev; Here is a reader (String xml is the name of your xml file): public boolean readXML(String xml) { rolev = new ArrayList<String>(); Document dom; // Make an instance of the DocumentBuilderFactory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // use the factory to take an instance of the document builder DocumentBuilder db = dbf.newDocumentBuilder(); // parse using the builder to get the DOM mapping of the // XML file dom = db.parse(xml); Element doc = dom.getDocumentElement(); role1 = getTextValue(role1, doc, "role1"); if (role1 != null) { if (!role1.isEmpty()) rolev.add(role1); } role2 = getTextValue(role2, doc, "role2"); if (role2 != null) { if (!role2.isEmpty()) rolev.add(role2); } role3 = getTextValue(role3, doc, "role3"); if (role3 != null) { if (!role3.isEmpty()) rolev.add(role3); } role4 = getTextValue(role4, doc, "role4"); if ( role4 != null) { if (!role4.isEmpty()) rolev.add(role4); } return true; } catch (ParserConfigurationException pce) { System.out.println(pce.getMessage()); } catch (SAXException se) { System.out.println(se.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } return false; } And here a writer: public void saveToXML(String xml) { Document dom; Element e = null; // instance of a DocumentBuilderFactory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // use factory to get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); // create instance of DOM dom = db.newDocument(); // create the root element Element rootEle = dom.createElement("roles"); // create data elements and place them under root e = dom.createElement("role1"); e.appendChild(dom.createTextNode(role1)); rootEle.appendChild(e); e = dom.createElement("role2"); e.appendChild(dom.createTextNode(role2)); rootEle.appendChild(e); e = dom.createElement("role3"); e.appendChild(dom.createTextNode(role3)); rootEle.appendChild(e); e = dom.createElement("role4"); e.appendChild(dom.createTextNode(role4)); rootEle.appendChild(e); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // send DOM to file tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(xml))); } catch (TransformerException te) { System.out.println(te.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } } catch (ParserConfigurationException pce) { System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce); } } getTextValue is here: private String getTextValue(String def, Element doc, String tag) { String value = def; NodeList nl; nl = doc.getElementsByTagName(tag); if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) { value = nl.item(0).getFirstChild().getNodeValue(); } return value; } Add a few accessors and mutators and you are done!
Jame at Stack Overflow Visit the source
Other answers
this is a good tutorial to start with http://totheriver.com/learn/xml/xmltutorial.html
Nammari
Srikanth Venkatesh
Related Q & A:
- How To Read Pdf Files On Nokia C503?Best solution by nds1.nokia.com
- How to Read xml file in java?Best solution by Stack Overflow
- How to Read Binary File to XML?Best solution by SharePoint
- How to convert XML files to PDF files?Best solution by Super User
- How to write temporary files from temporary path to a temporary directory?Best solution by msdn.microsoft.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.