The SAX parser provides more efficient way to read large xml
than DOM parser. The example will show how to read an xml file by using SAX
parser.
Content.java
package
org.metadata.core.xml;
public class Content {
private String value;
private String color;
public String
getValue() {
return value;
}
public void
setValue(String value) {
this.value = value;
}
public String
getColor() {
return color;
}
public void
setColor(String color) {
this.color = color;
}
}
|
XMLFileReader.java
package
org.metadata.core.xml;
import
java.io.CharArrayWriter;
import
java.util.ArrayList;
import
java.util.List;
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 XMLFileReader
{
private class Reader extends
DefaultHandler {
private
List<Content> contentList = new
ArrayList<Content>();
private Content content = null;
CharArrayWriter text = null;
public void
startElement(String uri, String localName, String qName, Attributes
attributes) throws SAXException {
text = new
CharArrayWriter();
if
(qName.equalsIgnoreCase("LINE")) {
content = new Content();
contentList.add(content);
}
}
public void
endElement(String uri, String localName, String qName) throws SAXException
{
if
(qName.equalsIgnoreCase("CONTENT")) {
content.setValue(getText());
} else if
(qName.equalsIgnoreCase("COLOR")) {
content.setColor(getText());
}
}
public void characters(char[] ch, int start, int length) throws SAXException
{
text.write(ch,
start, length);
}
public
List<Content> getContentList() {
return contentList;
}
public String
getText() {
return text.toString().trim();
}
}
public
List<Content> getContentList() {
Reader reader = new Reader();
try {
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser saxParser =
factory.newSAXParser();
saxParser.parse("resources/sample.xml", reader);
} catch (Exception e)
{
e.printStackTrace();
}
return
reader.getContentList();
}
public static void main(String[]
argv) {
XMLFileReader xmlReader = new
XMLFileReader();
List<Content> contentList =
xmlReader.getContentList();
for (Content c :
contentList) {
System.out.println(c.getValue()
+ "
- " + c.getColor());
}
}
}
|
- Create a folder name with “resources” and set the folder into the classpath.
- Put the “sample.xml” file into the “resources” folder.
sample.xml
<?xml
version="1.0" encoding="UTF-8"?>
<noties xsi:noNamespaceSchemaLocation="sample.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<notic>
<line>
<content>Mutu</content>
<color>#0052415</color>
</line>
<line>
<content>Zaw Than Oo</content>
<color>red</color>
</line>
<line>
<content>John Smith</content>
<color>blue</color>
</line>
<line>
<content>CycDemo</content>
<color></color>
</line>
</notic>
</noties>
|
Complete Package Structure
No comments:
Post a Comment