0% found this document useful (0 votes)
68 views26 pages

Log4j Index: What Is Log4j, Why Log4j Came Into Picture

The document provides an overview of Log4j, a logging framework for Java applications. It discusses: - Why Log4j was created to overcome limitations of print statements - The main components of Log4j - Logger, Appender, and Layout - A basic "Hello World" example using FileAppender to log messages to a file - How to configure Log4j using a properties file to specify the appender and layout

Uploaded by

subhjit
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views26 pages

Log4j Index: What Is Log4j, Why Log4j Came Into Picture

The document provides an overview of Log4j, a logging framework for Java applications. It discusses: - Why Log4j was created to overcome limitations of print statements - The main components of Log4j - Logger, Appender, and Layout - A basic "Hello World" example using FileAppender to log messages to a file - How to configure Log4j using a properties file to specify the appender and layout

Uploaded by

subhjit
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

Log4j index

What Is Log4j, Why Log4j Came Into Picture What Are The Main Components Of Log4J Log4j Hello World Program How To Create Log4j.properties File Example On Log4j.properties File With FileAppender & SimpleLayout Log4j Example On Using FileAppender And ConsoleAppender Simultaneously

What Is Log4j, Why Log4j Came Into Picture


While developing Java/J2EE applications, for debugging an application that is to know the status of a java application at its execution time, in general we use system.out.println statements in the application right But we have some disadvantages while using SOPL (system.out.println) statements. Generally SOPL statements are printed on console, so there are temporary messages and when ever the console is closed then automatically the messages are removed from the console It is not possible to store the SOPL messages in a permanent place and these are single threaded model, means these will prints only one by one message on the console screen In order to overcome the problems of SOPL statements Log4j came into picture, with Log4j we can store the flow details of our Java/J2EE in a file or databases This is a Open Source tool given by Apache, for only java projects, to record or write the status of an application at various places Working with log4j is nothing but working with classes & interfaces given in org.apache.log4j.* Log4j is a common tool, used for small to large scale Java/J2EE projects In Log4j we use log statements rather SOPL statements in the code to know the status of a project while it is executing In real time, after a project is released and it is installed in a client location then we call the location as onsite right, when executing the program at on-site location, if we got any problems occurred then these problems must report to the off showered engineers, in this time we used to mail these Log files only so that they can check the problems easily

What Are The Main Components Of Log4J


We have mainly 3 components to work with Log4j

Logger Appender Layout

Logger

Logger is a class, in org.apache.log4j.* We need to create Logger object one per java class

This component enables Log4j in our java class Logger methods are used to generate log statements in a java class instead of sopls So in order to get an object of Logger class, we need to call a static factory method [ factory method will gives an object as return type ] We must create Logger object right after our class name, i will show you

Getting Logger Object


static Logger log = Logger.getLogger(YourClassName.class.getName()) Note: while creating a Logger object we need to pass either fully qualified class name or class object as a parameter, class means current class for which we are going to use Log4j.

Example
1public class Client { 2 3 static Logger l = Logger.getLogger(Client.class.getName()); 4 public static void main(String[] args) { 5 // Our logic will goes here 6 } 7 } 8 Logger object has some methods, actually we used to print the status of our application by using these methods only We have totally 5 methods in Logger class

debug() info() warn() error() fetal()

As a programmer its our responsibility to know where we need to use what method, did you observe there ? method names are different right, but all are same

Priority Order
debug < info < warn < error < fatal I mean, fatal is the highest error like some database down/closed

Remember: Friends dont confuse by seeing all these 5 methods all are same, for example if our application is about 100 lines and we have JDBC related code in some 45th line or some where there we used to write fatal() method. All it could be is just for human identification purpose names are different, else these 5 methods will print one text message only You will get more clarity once you saw the first program on log4j.

Appender
Appender job is to write the messages into the external file or database or smtp

Logger classes generates some statements under different levels right, this Appender takes these log statements and stores in some files or database Appender is an interface

In log4j we have different Appender implementation classes


FileAppender [ writing into a file ] ConsoleAppender [ Writing into console ] JDBCAppender [ For Databases ] SMTPAppender [ Mails ] SocketAppender [ For remote storage ] SocketHubAppender SyslogAppendersends TelnetAppender

Again in FileAppender we have 2 more


RollingFileAppender DailyRollingFileAppender

For now just remember, i will explain while executing the program

Layout
This component specifies the format in which the log statements are written into the destination repository by the appender We have different type of layout classes in log4j

SimpleLayout PatternLayout HTMLLayout XMLLayout

Log4j Hello World Program

For working with log4j, we must set log4j.jar in our class path

Files Required

Client.java my.txt [ We will let the appender to write into this file ]

Directory Structure Client.java


1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9
import import import import import org.apache.log4j.Appender; org.apache.log4j.FileAppender; org.apache.log4j.Layout; org.apache.log4j.Logger; org.apache.log4j.SimpleLayout;

public class Client { static Logger l = Logger.getLogger(Client.class.getName()); public static void main(String[] args) { Layout l1 = new SimpleLayout(); Appender a; //Appender a = new ConsoleAppender(l1); try { a = new FileAppender(l1,"my.txt", false); // 3rd parameter is true by default // true = Appends the data into my.txt // false = delete previous data and re-write l.addAppender(a); } catch(Exception e) {} l.fatal("This is the error message.."); System.out.println("Your logic executed successfully....");

} }

2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 Once we run this client program, my.txt will contains.

my.txt
FATAL This is the error message..

Explanation

First step is to create one Logger class object [ see line number 9 ] Second step is to create Layout object [ see line number 13 ] Once Layout is ready, our next step is to create Appender [ see line number 18 ] In appender i have passed 3 parameters like.. first parameter is object of layout because, appender will write the error messages based on the layout we selected, then 2nd parameter is file name with extension [ in this file only appender will writes the messages ], then 3rd parameter is by default true, means appender will appends the error messages, if we give false then appender will clears the previous data in my.txt file and write newly

Hey see, i have used FileAppender, but if i would like to change my appender choice to ConsoleAppender, then again we must open this java file then modifications and recompile bla bla, so to avoid this we can use one .properties file, will see this in the next session.

How To Create Log4j.properties File


In previous program, i have used FileAppender. But if i would like to change my appender to JDBCAppender, i have to open my java file and do the modifications and need to recompile. We can avoid this by writing one .properties file. By default the file name would be log4j.properties. This properties file stores data in the form of key, values pairs, in this file keys are fixed but values are our own. We can include all the log4j related properties into this file.

log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,LOGFILE log4j.appender.CONSOLE= log4j.appender.CONSOLE.layout= log4j.appender.CONSOLE.layout.ConversionPattern= log4j.appender.LOGFILE= log4j.appender.LOGFILE.File= log4j.appender.LOGFILE.MaxFileSize= log4j.appender.LOGFILE.layout= log4j.appender.LOGFILE.layout.ConversionPattern=

Example On Log4j.properties File With FileAppender & SimpleLayout


Let us see how to use log4j.properties file

Files Required

Client.java log4j.properties my.txt [ We will let the appender to write into this file ]

Directory Structure Client.java


1 import org.apache.log4j.Logger; 2 3 public class Client { 4 static Logger l = Logger.getLogger(Client.class.getName()); 5

6 7 8 9 1 0 public static void main(String[] args) { 1 1 l.debug("This is debug message"); 1 l.info("This is info message"); 2 l.warn("This is warn message"); l.fatal("This is fatal message"); 1 l.error("This is error message"); 3 1 System.out.println("Your logic executed successfully...."); 4 1 } 5 } 1 6 1 7 1 8 Once we run this client program, my.txt will contains.

log4j.properties
log4j.rootLogger = DEBUG,abc log4j.appender.abc = org.apache.log4j.FileAppender log4j.appender.abc.file = my.txt log4j.appender.abc.layout = org.apache.log4j.SimpleLayout

my.txt
DEBUG This is debug message INFO This is info message WARN This is warn message FATAL This is fatal message ERROR This is error message

Execution Flow

Run Client.java Log4j environment created, at line number 5

As our default properties file name is log4j.properties, we no need to import properties file explicitly into Client.java, by default our java class will verify for the properties file named log4j.properties. If we give the name other than log4j to the properties we have to import manually into our java class [ will see this later, like how to manually ] So once Logger object created at line number 5, our class will be able to know about the content in log4j.properties In log4j.properties the content always will be in key,value pairs only

Explanation

If we use .properties file, we no need to import any related classes into our java class log4j.rootLogger = DEBUG,abc > Here DEBUG means we are specifying the level from where log4j methods execution must start, see my.txt file it showing all messages right. But if we wrote log4j.rootLogger = WARN,abc then it will prints the messages in l.warn(), l.error(), l.fatal() and ignores l.debug(), l.info() I have used FileAppender as my Appender, so if we want to change my appender to ConsoleAppender, i will open log4j.properties file and do the modifications, so no need to touch our java classes, this is the main advantage of .properties file

So just change layout into HTMLLayout and check the output

Log4j Example On Using FileAppender And ConsoleAppender Simultaneously


Let us see how to use FileAppender and ConsoleAppender at a time.

Files Required

Client.java log4j.properties my.txt [ We will let the appender to write into this file ]

Directory Structure Client.java


1 import org.apache.log4j.Logger; 2 3 public class Client { 4 static Logger l = Logger.getLogger(Client.class.getName()); 5 6 public static void main(String[] args) { 7

8 9 1 0 1 1 1 2 1 3 1 4 1 5 } 1 6 } 1 7 1 8 1 9

l.debug("This is debug message"); l.info("This is info message"); l.warn("This is warn message"); l.fatal("This is fatal message"); l.error("This is error message"); System.out.println("Your logic executed successfully....");

Once we run this client program, my.txt will contains.

log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,LOGFILE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x %m%n log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender log4j.appender.LOGFILE.File=my.txt log4j.appender.LOGFILE.MaxFileSize=1kb log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=[%t] %-5p %c %d{dd/MM/yyyy HH:mm:ss} %m%n

my.txt
[main] DEBUG Client 27/02/2012 21:39:15 This is debug message [main] INFO Client 27/02/2012 21:39:15 This is info message [main] WARN Client 27/02/2012 21:39:15 This is warn message

[main] FATAL Client 27/02/2012 21:39:15 This is fatal message [main] ERROR Client 27/02/2012 21:39:15 This is error message

Output In Eclipse Console

Design pattern questions for Beginners


1. Can you name few design patterns used in standard JDK library? Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer pattern which is used in Swing and many event listener frameworks. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java.

When to use Factory design pattern in Java



Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework. Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product. Factory method is used when Products don't need to know how they are created. We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided

Code Example of Factory Design Pattern in Java:


Lets see an example of how factory pattern is implemented in Code.We have requirement to create multiple currency e.g. INR, SGD, USD and code should be extensible to accommodate new Currency as well. Here we have made Currency as interface and all currency would be concrete implementation of Currency interface. Factory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible. Here is complete code example of Factory pattern in Java: interface Currency { String getSymbol(); } // Concrete Rupee Class code

class Rupee implements Currency { @Override public String getSymbol() { return "Rs"; } } // Concrete SGD class Code class SGDDollar implements Currency { @Override public String getSymbol() { return "SGD"; } } // Concrete US Dollar code class USDollar implements Currency { @Override public String getSymbol() { return "USD"; } } // Factroy Class code class CurrencyFactory { public static Currency createCurrency (String country) { if (country. equalsIgnoreCase ("India")){ return new Rupee(); }else if(country. equalsIgnoreCase ("Singapore")){ return new SGDDollar(); }else if(country. equalsIgnoreCase ("US")){ return new USDollar(); } throw new IllegalArgumentException("No such currency"); } } // Factory client code public class Factory { public static void main(String args[]) { String country = args[0]; Currency rupee = CurrencyFactory.createCurrency(country); System.out.println(rupee.getSymbol()); } }

Advantage of Factory method Pattern in Java:


Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In following are main advantages of using Factory pattern in Java: 1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code? E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?

2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory. 3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side. 4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.

Java DOM Tutorial


Document Object Model: DOM is a platform- and language-neutral interface, that provides a standard model of how the objects in an XML object are put together, and a standard interface for accessing and manipulating these objects and their inter-relationships. The DOM is an interface that exposes an XML document as a tree structure comprised of nodes. The DOM allows you to programmatically navigate the tree and add, change and delete any of its elements. The DOM programming interface standards are defined by the World Wide Web Consortium (W3C) . The W3C site provides a comprehensive reference of the XML DOM.

Creating Blank DOM Document


This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.

DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");

Creating Blank DOM Document Posted on: February 26, 2008 at 12:00 AM This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents.

Creating Blank DOM Document

This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.

DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");

The instance of the class DocumentBuilder is used to create a blank document. The newDocument() method of the class returns a blank DOM document.
Document doc = parser.newDocument(); Here is the full code of CreateBlankDocument.java import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CreateBlankDocument { public static void main(String[] args) {

System.out.println("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder parser = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = parser.newDocument(); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println("Done..."); System.out.println("Exiting..."); } }

Creating DOM Child Elements


This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.

DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");

Creating Blank DOM Document Posted on: February 26, 2008 at 12:00 AM

This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents.

Creating Blank DOM Document

This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.

DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");

The instance of the class DocumentBuilder is used to create a blank document. The newDocument() method of the class returns a blank DOM document.
Document doc = parser.newDocument(); Here is the full code of CreateBlankDocument.java import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CreateBlankDocument { public static void main(String[] args) { System.out.println("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder parser = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = parser.newDocument();

}catch(Exception e){ System.out.println(e.getMessage()); } System.out.println("Done..."); System.out.println("Exiting..."); } }

Creating DOM Child Elements


In the previous lesson you learned how to create DocumentBuilder object and the create a blank DOM document. The following code creates a blank document. //Create blank DOM Document Document doc = docBuilder.newDocument(); The createElement function is used to create the root element and appendChild method is used to append the element to the DOM document. //create the root element Element root = doc.createElement("root"); //all it to the xml tree doc.appendChild(root); Adding Comment Element to DOM Tree The doc.createComment function is used to create Comment object. //create a comment Comment comment = doc.createComment("This is comment"); //add in the root element root.appendChild(comment); Adding Child Element to DOM Tree The doc.createElement function is used to create Child element. //create child element Element childElement = doc.createElement("Child"); //Add the atribute to the child childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement);

Printing the DOM Tree on console An finally we will print the DOM tree on the console with the following code: TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); Here is the full code of CreateDomXml.java
import org.w3c.dom.*; import import import import javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;

class CreateDomXml { public static void main(String[] args) { try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = docBuilder.newDocument(); //create the root element Element root = doc.createElement("root"); //all it to the xml tree doc.appendChild(root); //create a comment Comment comment = doc.createComment("This is comment"); //add in the root element root.appendChild(comment); //create child element Element childElement = doc.createElement("Child"); //Add the atribute to the child childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); }catch(Exception e){ System.out.println(e.getMessage()); } } }

Getting The XML Root Element


After reading this section, you will be able to retrieve a root element from the XML document. The JAXP (Java APIs for XML Processing) provides a common interface for creating and using xml files using the standard SAX, DOM and XSLTs. Here you will see the given example to use DOM interface. Description of program: You need a XML document (file). Both Java and the XML file are kept in the same directory. This program takes a XML file as a String at the console . If the given file exists then it parses the document using parse() method . Before parsing the XML document you need a DocumentBuilder object. For creating this first of all you create a DocumentBuilderFactory. After parsing the XML document you get the node element using getDocumentElement() method. To get the root element use the getNodeName() method.

Getting The XML Root Element

After reading this section, you will be able to retrieve a root element from the XML document. The JAXP (Java APIs for XML Processing) provides a common interface for creating and using xml files using the standard SAX, DOM and XSLTs. Here you will see the given example to use DOM interface. Description of program: You need a XML document (file). Both Java and the XML file are kept in the same directory. This program takes a XML file as a String at the console . If the given file exists then it parses the document using parse() method . Before parsing the XML document you need a DocumentBuilder object. For creating this first of all you create a DocumentBuilderFactory. After parsing the XML document you get the node element using getDocumentElement() method. To get the root element use the getNodeName() method.

Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Here is the Java File: GetRootNode.java
import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class GetRootNode{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter xml file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = fact.newDocumentBuilder(); Document doc = builder.parse(str); Node node = doc.getDocumentElement(); String root = node.getNodeName(); System.out.println("Root Node: " + root); } else{ System.out.println("File not found!");

} } catch(Exception e){} }

Output of the program: C:\vinod\xml>javac GetRootNode.java C:\vinod\xml>java GetRootNode Enter xml file name: Employee-Detail.xml Root Node: Employee-Detail

To Count XML Element

To Count XML Element Posted on: June 4, 2007 at 12:00 AM In this section, you will learn to count the elements present in a XML file using DOM APIs.

To Count XML Element

In this section, you will learn to count the elements present in a XML file using DOM APIs. Description of program: This program helps to count the XML element. It takes a xml file (as a string ) at the console and checks its availability. It parses the xml document using the parse() method. After parsing the XML document it asks for element name which have to count. Create a NodeList and use the getElementByTagName() method. The getLength() method counts the occurrences of the specified element. If the asked element is not available( i.e.. the given element isn't found) it returns 0. Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail>

<Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Here is the Java File: DOMCountElement.java
import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class DOMCountElement{ public static void main(String[] args) { try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Create the builder and parse the file Document doc = factory.newDocumentBuilder().parse(xmlFile); System.out.print("Enter element name: "); String element = bf.readLine(); NodeList nodes = doc.getElementsByTagName(element); System.out.println("xml Document Contains " + nodes.getLength() + " elements."); } else{ System.out.print("File not found!");

} } catch (Exception ex) { System.out.println(ex); } }

Create - XML File (Document) import


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

java.io.*;

public class CreatXMLFile { 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); transformer.transform(source, result); } }

Getting all XML Elements


Description of program: The following program helps you in getting all XML elements displayed on the console. This program asks for a xml file name and checks its availability. whether the given file exists or not in the same directory. So, you need a XML file (Employee-Detail.xml) that contains some elements. Program parses the xml file using the parse() method and creates a Document object Tree. DocumentBuilder object helps you to get features to parse the XML file. After parsing the XML file a NodeList is created using the getElementsByTagName().This NodeList object creates element. Elements name are retrieved using the getNodeName() method. Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail>

Google Advance Search RoseIndia.Net Search

Getting all XML Elements Posted on: June 8, 2007 at 12:00 AM In this section, you will learn to retrieve all elements of the XML file using the DOM APIs.

Getting all XML Elements

In this section, you will learn to retrieve all elements of the XML file using the DOM APIs. This APIs provides some constructors and methods which helps us to parse the XML file and retrieve all elements. Description of program: The following program helps you in getting all XML elements displayed on the console. This program asks for a xml file name and checks its availability. whether the given file exists or not in the same directory. So, you need a XML file (Employee-Detail.xml) that contains some elements. Program parses the xml file using the parse() method and creates a Document object Tree. DocumentBuilder object helps you to get features to parse the XML file. After parsing the XML file a NodeList is created using the getElementsByTagName().This NodeList object creates element. Elements name are retrieved using the getNodeName() method. Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name>

<Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Here is Java File: DOMElements.java


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

public class DOMElements{ 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()){ // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); System.out.println("XML Elements: "); for (int i=0; i<list.getLength(); i++) { // Get element Element element = (Element)list.item(i); System.out.println(element.getNodeName()); } } else{ System.out.print("File not found!"); } } catch (Exception e) { System.exit(1); } } }

Download this example. Output of this program: C:\vinod\xml>javac DOMElements.java

C:\vinod\xml>java DOMElements Enter XML File name: Employee-Detail.xml XML Elements: Employee-Detail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail

Getting Dom Tree Elements and their Corresponding XML Fragments

You might also like