Getting Attributes And its Value
In this section, you will learn to retrieve the
attributes and their value from a XML document using the SAX APIs.
Description of program:
This program helps you in retrieving attributes and
their values. The parse() method is invoked by the SAXParser
object. Override
startElement() method in
SAXHandler
class to provide functionality to get the attribute and its
value from a xml file.
Here is the XML File: sample.xml
<Employee-detail >
<Employee name="Amit" >
<address>My address</address>
</Employee>
<issued-items>
<item code="111" type="CD" label=" music" />
<item code="222" type="DVD" label=" video"/>
</issued-items>
</Employee-detail> |
Here is the Java File: ReadAttributes.java
import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.util.* ;
import org.apache.xerces.impl.*;
import org.apache.xerces.parsers.*;
import org.apache.xerces.jaxp.*;
public class ReadAttributes {
public static void main(String[] args) {
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);
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<length; 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);
}
}
}
}
|
Download this example.
Output of this program:
C:\vinod\xml\sax1>javac ReadAttributes.java
C:\vinod\xml\sax1>java ReadAttributes
Enter a xml file name: sample.xml
Name: Value:
name Amit
code 111
type CD
label music
code 222
type DVD
label video |