Sunday, June 19, 2016

Xml SAX and DOM Parser

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

public class create {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number to add elements in your XML file: ");
String str = bf.readLine();
int no = Integer.parseInt(str);
System.out.print("Enter root: ");
String root = bf.readLine();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(root);
        document.appendChild(rootElement);
for (int i = 1; i <= no; i++){
System.out.print("Enter the element: ");
String element = bf.readLine();
System.out.print("Enter the data: ");
String data = bf.readLine();
Element em = document.createElement(element);
em.appendChild(document.createTextNode(data));
rootElement.appendChild(em);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result =  new StreamResult(System.out);
StreamResult result1 =  new StreamResult("new.xml");
        transformer.transform(source, result);

transformer.transform(source, result1);
}
}import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class elecount {

  public static void main(String argv[]) {

try {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("catalog.xml");

NodeList list = doc.getElementsByTagName("CD");

System.out.println("Total of elements : " + list.getLength());

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
  }
}import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class elements{
public static void main(String[] args) {
try{
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
System.out.println("XML Elements: ");
DefaultHandler handler = new DefaultHandler(){
public void startElement(String uri, String lName, String ele, Attributes attributes)throws SAXException{
//print elements of xml
System.out.println(ele);
}
};
parser.parse("catalog.xml", handler);
}
catch (Exception e){
e.printStackTrace();
}
}
}import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

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

File file = new File("catalog.xml");
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse("catalog.xml");
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}
}import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;


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

File file = new File("catalog.xml");
if (file.exists()){
//SAX-implementation:
SAXParserFactory factory = SAXParserFactory.newInstance();
// Create SAX-parser
SAXParser parser = factory.newSAXParser();
System.out.println("Name:\t" + "Value:");
//Define a handler
SaxHandler handler = new SaxHandler();
// Parse the xml document
parser.parse(xmlFile, handler);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e) {
e.printStackTrace();
}
}

private static class SaxHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXParseException,SAXException {
int length = attrs.getLength();
//Each attribute
for (int i=0; i // Get names and values to each attribute
String name = attrs.getQName(i);
System.out.print(name);
                String value = attrs.getValue(i);
System.out.println("\t"+value);
}
}
}
}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 readsax {


   public static void main(String argv[]) {


    try {

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

DefaultHandler handler = new DefaultHandler() {

boolean title = false;
boolean artist = false;
boolean company = false;
boolean price = false;
        boolean year = false;

public void startElement(String uri, String localName,String qName,
                Attributes attributes) throws SAXException {

System.out.println("Start Element :" + qName);

if (qName.equalsIgnoreCase("TITLE")) {
title = true;
}

if (qName.equalsIgnoreCase("ARTIST")) {
artist = true;
}

if (qName.equalsIgnoreCase("COMPANY")) {
company = true;
}

if (qName.equalsIgnoreCase("PRICE")) {
price = true;
}


if (qName.equalsIgnoreCase("YEAR")) {
year = true;
}

}

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

System.out.println("End Element :" + qName);

}

public void characters(char ch[], int start, int length) throws SAXException {

if (title) {
System.out.println("Title : " + new String(ch, start, length));
title = false;
}

if (artist) {
System.out.println("Artist : " + new String(ch, start, length));
artist = false;
}

if (company) {
System.out.println("Company : " + new String(ch, start, length));
company = false;
}

if (price) {
System.out.println("Price : " + new String(ch, start, length));
price = false;
}


if (year) {
System.out.println("Year : " + new String(ch, start, length));
year = false;
}
}

     };

       saxParser.parse("catalog.xml", handler);

     } catch (Exception e) {
       e.printStackTrace();
     }

   }

}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class readxml{
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
// Create transformer
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Output text type
//tFormer.setOutputProperty(OutputKeys.METHOD, "text");
// Write the document to a file
Source source = new DOMSource(doc);
Result result = new StreamResult(System.out);
tFormer.transform(source, result);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class rmelement {
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
System.out.print("Enter an element which have to delete: ");
String remElement = bf.readLine();
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer tFormer = tFactory.newTransformer();
Element element = (Element)doc.getElementsByTagName(remElement).item(0);
// Remove the node
element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
doc.normalize();
Source source = new DOMSource(doc);
Result dest = new StreamResult(System.out);
tFormer.transform(source, dest);
System.out.println();
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;

public class SearchElement{
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();
System.out.print("Enter element that have to count: ");
String ele = bf.readLine();
NodeList list = doc.getElementsByTagName(ele);
if(list.getLength() == 0){
System.out.println("Element doesn't exist in the " + str + " Document.");
}
else{
System.out.println("Element occurrs " + list.getLength() + " times in the " + str);
}
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
e.getMessage();
}
}
}
import org.w3c.dom.*;
import org.w3c.dom.Node;
import javax.xml.parsers.*;
public class totaltext{
    public static boolean isTextNode(Node n){
    return n.getNodeName().equals("#text");
  }
    public static void main(String[]args)throws Exception{
  DocumentBuilderFactory docFactory =  DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  Document doc = docBuilder.parse("catalog.xml");

          Element  root = doc.getDocumentElement();

System.out.println(root.getNodeName());        

 NodeList nl = root.getChildNodes();
 
         
for(int i=0; i            Node ele = nl.item(i);
            if(isTextNode(ele)){

           continue;
}
         
 System.out.print("\n\n"+ele.getNodeName()+":  ");
            System.out.println(ele.getFirstChild().getNodeValue()+"\t ");

 NodeList innernl= ele.getChildNodes();

            for(int j=0; j            Node node = innernl.item(j);
            if(isTextNode(node))
              continue;
            System.out.print("\n\n"+node.getNodeName()+":  ");
            System.out.print(node.getFirstChild().getNodeValue()+"\t ");
         


}
          System.out.println();
        }
    }
}

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...