Searching...
Wednesday, 19 September 2012

Java XML DOM Parser Modify XML Example

02:59

 

DOM Parser classes

DocumentBuilder –> This class defines the API to obtain DOM Document instances from an XML document.
DocumentBuilderFactory –> Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
Transformer –> An instance of this abstract class can transform a source tree into a result tree.
TransformerFactory –> A TransformerFactory instance can be used to create Transformer and Template objects.
Document->The Document interface represents the entire HTML or XML document.
Element –>The Element interface represents an element in an HTML or XML document.
Node –> The Node interface is the primary datatype for the entire Document Object Model.
NodeList –>The NodeList interface provides the abstraction of an ordered collection of nodes.
DOM Parser Modify XML Example

Sample XML file

<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<Order>
<Ordernumber Number="9988">
<OrderedItem1>Pepsi</OrderedItem1>
<OrderitemPrice>10</OrderitemPrice>
<OrderitemTax>10</OrderitemTax>
<OrderDiscount>20</OrderDiscount>
</Ordernumber>
</Order>
Sample Java Program to modify xml file
1. Update Order number
2. Update Order price
3. Removing orderDiscount
4. Adding OrderCoupon
package mycollectiontest;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLParser {

public static void main(String[] args) {
try {
String filepath = "order.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);

// Get the ordernumberelement
Node ordernumber = doc.getElementsByTagName("Ordernumber").item(0);

// update ordernumberattribute
NamedNodeMap attributes = ordernumber.getAttributes();

Node nodeAttr = attributes.getNamedItem("Number");
nodeAttr.setTextContent("1111");

// append a new node to ordernumber
Element orderOffercoupon = doc.createElement("OrderCoupon");
orderOffercoupon.appendChild(doc.createTextNode("NEWYEAR"));
ordernumber.appendChild(orderOffercoupon);

// loop the ordernumberchild node
NodeList list = ordernumber.getChildNodes();
// Updating Order price
// Removing Order Discount
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if ("OrderitemPrice".equals(node.getNodeName())) {
node.setTextContent("100");
}
// Remove OrderDiscount Element
if ("OrderDiscount".equals(node.getNodeName())) {
ordernumber.removeChild(node);
}
}
// Writing to xmlfile
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Updation completed.. Please check order.xml");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}

}
Output xml file
<?xmlversion="1.0"encoding="UTF-8"standalone="no"?>
<Order>
<Ordernumber Number="1111">
<OrderedItem1>Pepsi</OrderedItem1>
<OrderitemPrice>100</OrderitemPrice>
<OrderitemTax>10</OrderitemTax>
<OrderCoupon>NEWYEAR</OrderCoupon>
</Ordernumber>
</Order>
Reference
docs.oracle.com

0 comments: