Showing posts with label Java XML. Show all posts
Showing posts with label Java XML. Show all posts

Java XML DOM4J Creating XML file Example

What is DOMJ4?
Dom4j is simple and easy to use open source library for Java XML,XPath and XSLT. This api will support DOM, SAX and JAXP.It is highly flexible and more memory efficient implementations of this framework.

Features of DOM4J

  • High flexible and memory efficient 
  • Support for Java collection framework while working with xml 
  • Support for JAXP,SAX,DOM,XSLT. 
  • It can work with large xml documents. 
  • Support XPath ,XSLT

DOM4J Creating XML file Example

Add below dependency in your pom.xml

<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
Or Download dom4j Jar from below repository
http://dom4j.sourceforge.net/

Important classes used

org.dom4j.Document->Specify xml documents
org.dom4j.DocumentHelper->Creates Document
org.dom4j.Element->Specify Element
org.dom4j.io.XMLWriter->Writes XML

Java class to create XML

package mycollectiontest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.*;

public class XMLExample {

public static void main(String[] args) {

// Creating document
Document document = DocumentHelper.createDocument();
Element order = document.addElement("Order");

// Creating element and setting attribute
Element orderNumber = order.addElement("OrderNumber");
orderNumber.addAttribute("Number", "1000");

// Creating other elements
Element orderItem = orderNumber.addElement("OrderItem");
orderItem.setText("Pen Drive");
Element orderItemDesc = orderNumber.addElement("OrderItemDescription");
orderItemDesc.setText("Trancsend 8 gb Pen Drive");

Element orderItemPrice = orderNumber.addElement("OrderItemPrice");
orderItemPrice.setText("500");
Element orderItemTax = orderNumber.addElement("OrderItemTax");
orderItemTax.setText("50");
Element orderItemTotal = orderNumber.addElement("OrderItemTotal");
orderItemTotal.setText("450");
// Writing document contents to xml file
XMLWriter output = null;
try {
output = new XMLWriter(new FileWriter(new File("order.xml")));
output.write(document);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Completed");

}

}
Output
<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber Number="1000">
<OrderItem>Pen Drive</OrderItem>
<OrderItemDescription>Trancsend 8 gb Pen Drive</OrderItemDescription>
<OrderItemPrice>500</OrderItemPrice>
<OrderItemTax>50</OrderItemTax>
<OrderItemTotal>450</OrderItemTotal>
</OrderNumber>
</Order>
Reference
http://dom4j.sourceforge.net/

Java XML JDOM Modify XML Example

What is JDOM ?

JDOM is an open source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features. JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT. It uses external parsers to build documents.

JDOM Readng XML Example

Create a Maven project and update below dependency

<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>

Sample xml files to modify

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1000">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>7000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemDiscount>700</OrderItemDiscount>
<OrderItemTotal>5600</OrderItemTotal>
</OrderNumber>
</Order>
Create Java file to modify  XML file

package mycollectiontest;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import java.io.*;

public class XMLExample {

public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("orderSample.xml");
try {
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();

// Updating OrderNumber attribute
Element orderNumber = rootNode.getChild("OrderNumber");
orderNumber.getAttribute("number").setValue("1002");

// Adding new Element OrderCoupon
Element orderCoupon = new Element("orderCoupon").setText("NEWYEAROFFER");
orderNumber.addContent(orderCoupon);

// Updating OrderItemPrice
orderNumber.getChild("OrderItemPrice").setText("10000");

// Removing OrderItemDiscount element
orderNumber.removeChild("OrderItemDiscount");

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, new FileWriter("orderSample.xml"));

System.out.println("orderSample.xml...Updated");
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
} catch (JDOMException jdomException) {
System.out.println(jdomException.getMessage());
}
}

}

Output

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1002">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>10000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemTotal>5600</OrderItemTotal>
<orderCoupon>NEWYEAROFFER</orderCoupon>
</OrderNumber>
</Order>

Java XML JDOM Creating XML Example


What is JDOM ?

JDOM is an open source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features. JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT. It uses external parsers to build documents.

JDOM Readng XML Example

Create a Maven project and update below dependency

 <dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>

Or Download JDOM jar from http://www.jdom.org/downloads/index.html

Create Java file to create XML file

package mycollectiontest;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class XMLExample {

public static void main(String[] args) {
try {
//Creating Order Root element
Element order = new Element("Order");
Document doc = new Document(order);
doc.setRootElement(order);
// Creating OrderItem element
Element orderItem = new Element("OrderNumber");
// Setting Attributes
orderItem.setAttribute(new Attribute("number", "1000"));
// Setting contents
orderItem.addContent(new Element("OrderItem").setText("Phone"));
orderItem.addContent(new Element("OrderItemDescription")
.setText("Smart phone"));
orderItem.addContent(new Element("OrderItemPrice").setText("7000"));
orderItem.addContent(new Element("OrderItemTax").setText("700"));
orderItem.addContent(new Element("OrderItemDiscount")
.setText("700"));
orderItem.addContent(new Element("OrderItemTotal").setText("5600"));
// Adding orderItem element in to document
doc.getRootElement().addContent(orderItem);
// Creating next orderItem
Element orderItem1 = new Element("OrderNumber");
orderItem1.setAttribute(new Attribute("number", "1001"));
orderItem1.addContent(new Element("OrderItem").setText("Laptop"));
orderItem1.addContent(new Element("OrderItemDescription")
.setText("13 Inch"));
orderItem1.addContent(new Element("OrderItemPrice")
.setText("17000"));
orderItem1.addContent(new Element("OrderItemTax").setText("1700"));
orderItem1.addContent(new Element("OrderItemDiscount")
.setText("1700"));
orderItem1.addContent(new Element("OrderItemTotal")
.setText("15600"));

doc.getRootElement().addContent(orderItem1);
//Outputs a JDOM document as a stream of bytes. The outputter can manage many styles
//of document formatting, from untouched to pretty printed.
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("PretechJDOM.xml"));

System.out.println("PretechJDOM.xml.. has been created");
} catch (IOException io) {
System.out.println(io.getMessage());
}
}

}
Output

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1000">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>7000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemDiscount>700</OrderItemDiscount>
<OrderItemTotal>5600</OrderItemTotal>
</OrderNumber>
<OrderNumber number="1001">
<OrderItem>Laptop</OrderItem>
<OrderItemDescription>13 Inch</OrderItemDescription>
<OrderItemPrice>17000</OrderItemPrice>
<OrderItemTax>1700</OrderItemTax>
<OrderItemDiscount>1700</OrderItemDiscount>
<OrderItemTotal>15600</OrderItemTotal>
</OrderNumber>
</Order>

Java XML JDOM Reading XML Example


Java XML JDOM Reading XML Example

What is JDOM ?

JDOM is an open source Java-based document object model for XML that was designed specifically for the Java platform so that it can take advantage of its language features. JDOM integrates with Document Object Model (DOM) and Simple API for XML (SAX), supports XPath and XSLT. It uses external parsers to build documents.

JDOM Readng XML Example

Create a Maven project and update below dependency

<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
Or Download JDOM jar from http://www.jdom.org/downloads/index.html

Sample xml file to read

<?xmlversion="1.0"encoding="UTF-8"?>
<Order>
<OrderNumber number="1000">
<OrderItem>Phone</OrderItem>
<OrderItemDescription>Smart phone</OrderItemDescription>
<OrderItemPrice>7000</OrderItemPrice>
<OrderItemTax>700</OrderItemTax>
<OrderItemDiscount>700</OrderItemDiscount>
<OrderItemTotal>5600</OrderItemTotal>
</OrderNumber>
<OrderNumber number="1001">
<OrderItem>Laptop</OrderItem>
<OrderItemDescription>13 Inch</OrderItemDescription>
<OrderItemPrice>17000</OrderItemPrice>
<OrderItemTax>1700</OrderItemTax>
<OrderItemDiscount>1700</OrderItemDiscount>
<OrderItemTotal>15600</OrderItemTotal>
</OrderNumber>
</Order>
Create Java class to Read XML file
package mycollectiontest;

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class XMLParser {

public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("orderfile.xml");
try {
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("OrderNumber");
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
System.out.println("==============================");
System.out.println("OrderItem : "+ node.getChildText("OrderItem"));
System.out.println("OrderItemDescription : "+ node.getChildText("OrderItemDescription"));
System.out.println("OrderItemPrice : "+ node.getChildText("OrderItemPrice"));
System.out.println("OrderItemTax : "+ node.getChildText("OrderItemTax"));
System.out.println("OrderItemDiscount : "+ node.getChildText("OrderItemDiscount"));
System.out.println("OrderItemTotal : "+ node.getChildText("OrderItemTotal"));
System.out.println("==============================");
}
} catch (IOException ioException) {
System.out.println(ioException.getMessage());
} catch (JDOMException jdomException) {
System.out.println(jdomException.getMessage());
}}

}

Output

==============================
OrderItem : Phone
OrderItemDescription : Smart phone
OrderItemPrice : 7000
OrderItemTax : 700
OrderItemDiscount : 700
OrderItemTotal : 5600
==============================
==============================
OrderItem : Laptop
OrderItemDescription : 13 Inch
OrderItemPrice : 17000
OrderItemTax : 1700
OrderItemDiscount : 1700
OrderItemTotal : 15600
==============================

Reference

http://www.jdom.org
Wikipedia

Java XML SAX Parser Example

 

SAX Parser Example

SAX parser using callback function of org.xml.sax.helpers.DefaultHandler to informs clients of the XML document structure. We have to extend DefaultHandler and override few methods to achieve xml parsing.

The methods to override are

  • startDocument() and endDocument() – Method called at the start and end of an XML document.
  • startElement() and endElement() – Method called at the start and end of a document element.
  • characters() – Method called with the text contents in between the start and end tags of an XML document element.
The below example shows the uses of DefaultHandler to parse and XML document.

SAX Parser Classes

SAXParserFactory –> Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
SAXParser ->Defines the API that wraps an XMLReader implementation class.
DefaultHandler –>This class provides default implementations for all of the callbacks in the four core SAX2 handler classes

Sample xml file

<Order>
<Ordernumber Number="1111">
<OrderedItem1>Pepsi</OrderedItem1>
<OrderitemPrice>100</OrderitemPrice>
<OrderitemTax>10</OrderitemTax>
<OrderCoupon>NEWYEAR</OrderCoupon>
</Ordernumber>
</Order>

Create a Java file

package mycollectiontest;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLParser {

public static void main(String[] args) {
try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {
boolean borderedItem1 = false;
boolean borderitemPrice = false;
boolean borderitemTax = false;
boolean borderCoupon = false;

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("OrderedItem1")) {
borderedItem1 = true;
}
if (qName.equalsIgnoreCase("OrderitemPrice")) {
borderitemPrice = true;
}
if (qName.equalsIgnoreCase("OrderitemTax")) {
borderitemTax = true;
}
if (qName.equalsIgnoreCase("OrderCoupon")) {
borderCoupon = true;
}
}

public void endElement(String uri, String localName, String qName) throws SAXException {
}

public void characters(char ch[], int start, int length) throws SAXException {
if (borderedItem1) {
System.out.println("OrderedItem1 : " + new String(ch, start, length));
borderedItem1 = false;
}
if (borderitemPrice) {
System.out.println("OrderitemPrice : " + new String(ch, start, length));
borderitemPrice = false;
}
if (borderitemTax) {
System.out.println("OrderitemTax : " + new String(ch, start, length));
borderitemTax = false;
}
if (borderCoupon) {
System.out.println("OrderCoupon : " + new String(ch, start, length));
borderCoupon = false;
}
}
};
saxParser.parse("order.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}

}

Output

OrderedItem1 : Pepsi
OrderitemPrice : 100
OrderitemTax : 10
OrderCoupon : NEWYEAR

Reference

docs.oracle.com

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts