您的位置:首页 > 其它

XML解析器

2014-06-05 15:47 417 查看
XML解析器一般上有两种:DOM和SAX,各有优缺点。

DOM:将整个XML文件读到内存后解析不能读大文件,可以任意移动指针读取树下的节点。

SAX:从文件头部顺序扫描,可以读取大文件,只能读一次,不能回头。

DOM解析器范例:

DocumentBuilder db;
Document doc = null;

//第一步:获取DOM解析器工厂实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try
{
//第二步:创建DOM解析器
db = dbf.newDocumentBuilder();
//第三步:解析文档
doc = db.parse("src/com/great/xml/chp1/Students1.xml");
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

//第四步:遍历元素获取出元素的属性、子元素、文本
//获取所有Student标签的节点集合
NodeList nlStudent = doc.getElementsByTagName("Student");
for(int i = 0; i < nlStudent.getLength(); i++)
{
//获取学生节点
Element elStudent = (Element)nlStudent.item(i);

//(方法一:针对简单的属性)通过名称获取Student节点的id值
System.out.println("id:" + elStudent.getAttribute("id"));
//(方法二:针对属性值可能包含实体引用,应该获得 Attr 对象来检查表示属性值的可能相当复杂的子树。)通过名称获得属性节点
Attr attrId = elStudent.getAttributeNode("id");
System.out.println("id:" + attrId.getValue());

//获取Student节点下面的Name节点集合
NodeList nlName = elStudent.getElementsByTagName("Name");
for(int j = 0; j < nlName.getLength(); j++)
{
//获取Name标签的文本内容(注:标签对中的文本内容,要看成是这个标签的子节点)
System.out.println("Name:" + nlName.item(j).getFirstChild().getNodeValue());
//如果是节点是末节点,那么也可以用这样的方式来获取文本内容
System.out.println("Name:" + nlName.item(j).getTextContent());
//				System.out.println("nlName.item(j):" + nlName.item(j).hasChildNodes());
}

//获取Student节点下面的Sex节点集合
NodeList nlSex = elStudent.getElementsByTagName("Sex");
for(int j = 0; j < nlSex.getLength(); j++)
{
//获取Sex标签的文本内容(注:标签对中的文本内容,要看成是这个标签的子节点)
System.out.println("Sex:" + nlSex.item(j).getFirstChild().getNodeValue());
//如果是节点是末节点,那么也可以用这样的方式来获取文本内容
System.out.println("Sex:" + nlSex.item(j).getTextContent());
}
}


SAX解析范例:

使用 SAX 解析 XML 文档的步骤:

创建 SAXParserFactory 的实例

创建 SAXParser 的实例

创建 SAXParserHandler 类

使用 parse() 方法解析 XML 文档

SAXParser sp = null;
FileInputStream fis = null;

//第一步:获取SAX解析器工厂实例
SAXParserFactory spf = SAXParserFactory.newInstance();

try
{
//第二步:创建SAX解析器
sp = spf.newSAXParser();
//			//XML实体的单一输入源,也就是要处理的XML文档
//			InputSource ins = new InputSource(
//									new BufferedReader(
//											new FileReader("src/com/great/xml/chp1/Students1.xml")));
//实例化一个文件输入流
fis = new FileInputStream("src/com/great/xml/chp1/Students1.xml");

//第三步:解析文档,并指定文档处理程序
sp.parse(fis, new SaxParserHandler1());
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(fis != null)
{
try
{
fis.close();
fis = null;
}
catch (IOException e)
{
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  XML解析