Java 对XML解析

package selftest;

import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.*;

public class SAXHandler extends HandlerBase
{
private Hashtable table = new Hashtable();

private String currentElement = null;

private String currentValue = null;

public void setTable(Hashtable table)
{
this.table = table;
}

public Hashtable getTable()
{
return table;
}

public void startElement(String tag, AttributeList attrs)
throws SAXException
{
currentElement = tag;
String str = "";
for (int i = 0; i < attrs.getLength(); i++)
{
String name = attrs.getName(i);
str += ":"+attrs.getValue(i);
}
System.out.println(tag +"   "+str);
}

public void characters(char[] ch, int start, int length)
throws SAXException
{
currentValue = new String(ch, start, length);
}

public void endElement(String name) throws SAXException
{
if (currentElement.equals(name))
table.put(currentElement, currentValue);
}

public static void main(String[] args)
{
try
{
File file = new File("D:\\workspace\\ljs\\src\\selftest\\persons.xml");
FileReader fr = new FileReader(file);
SAXParserFactory factory =  SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
SAXHandler hander = new SAXHandler();
parser.parse(new InputSource(fr),hander);
Hashtable hashTable = hander.getTable();
Enumeration e = hashTable.keys();
while (e.hasMoreElements())
{
System.out.println(hashTable.get(e.nextElement()));
}

}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

你可能感兴趣的:(java,xml)