Posts

Showing posts with the label XML

Formating XML for Pretty Printing

The following Class is an example which we can use to Pretty Printing XML. method parseXmlString() reads a String and build a Document Object. method formatXMLString() uses Transformer Object's Outputproperties to set features like Encoding, Indentation etc. public class XmlFormatter { public String formatXMLString(String string) throws Exception { final Document document = parseXmlString(string); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "no"); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(document), new StreamResult(out)); return out.toString(); } private Document parseXmlString(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstan...

JDOM Parser to Read and Update XML

JDom is a java based library for processing XML.  It is light weight and fast. It is simple to use since it was designed for Java. JDom Documents can be used with DOM tree or SAX events. JDom Support XPath. The following examples shows some common usecases with JDom such as 1) Update the value of a node in the xml 2) Print the xml from JDom Document 3) Get a particular Node using XPath //Update the value of a node Document doc = new SAXBuilder().build(new File(fileToProcess)); Element rootElement = doc.getRootElement(); Element book = rootElement.getChild("book").getChild("author") .setText("Sidd"); //Print the xml XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, System.out); // Get a particular Node useing XPath XPath xPath = XPath.newInstance("/bookstore/book[bookid=$bookid]/bookid"); xPath.setVariable("bookid", "id1002"); Element guest = (Element) xPath.selectSingleNode(doc); System.out.pri...