`
ljs120ljs
  • 浏览: 7504 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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();
}

}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics