XML解析---dom解析和sax解析
目前XML解析的方法主要用两种: 1、dom解析:(Document Object Model,即文档对象模型)是W3C组织推荐的解析XML的一种方式。 使用dom解析XML文档,该解析器会先把XML文档加载到内存中,生成该XML文档对应的document对象,然后把XML文档中的各个标签元素变成
目前XML解析的方法主要用两种:
1、dom解析:(Document Object Model,即文档对象模型)是W3C组织推荐的解析XML的一种方式。使用dom解析XML文档,该解析器会先把XML文档加载到内存中,生成该XML文档对应的document对象,然后把XML文档中的各个标签元素变成相应的Element对象,文本会变成Text对象,属性会变成Attribute对象,并按这些标签、文本、属性在XML文档中的关系保存这些对象的关系。
缺点:消耗内存,所以使用dom解析XML文档时不能解析太大的XML文档,否则有可能会造成内存溢出。
优点:使用dom解析XML文档可以很方便的执行增删改查操作(可以直接根据节点对应的对象进行操作)。
2、sax解析:Simple API for XML,不是官方标准,但它是XML社区事实上的标准,几乎所有的XML解析器都支持它。
使用sax解析XML文档,该解析器会从上往下读,读一行,解析一行;
优点:因为它解析XML文档是采取读一行,解析一行的方式,所以它不会对内存造成压力。缺点:不适合执行增删改查的操作(也是因为它解析XML文档时采取的读一行解析一行的方式,所以它不能往回操作),只适合对XML文档进行读取操作。
======================================================================================================
补充:
XML解析开发包:Jaxp(sun)、Jdom、dom4j;
======================================================================================================
调整JVM内存大小:
当我们要解析的XML文档内存比较大、而且要对该XML中的节点数据进行相关的操作时,使用这两种解析方式显然都会不方便,这时就需要调整JVM内存的大小了。
JVM默认的允许最大内存容量是64M(根据jdk的版本不同,默认的最大容量值不一样,jdk5.0版本的是64MB,jdk7版本的是170MB)。
调整JVM内存大小的方法(相应的命令为:-Xmx内存大小值单位):
在Eclipse中的项目导航框中右击相应的Java程序》》Run As》》Open Run Dialog...》》打开Run对话框》》选择Arguments选项,在开窗口中有两个输入框,第一个是程序的参数输入框,第二个是VM的参数输入框,在第二个VM的参数输入框中输入Xmx200M》》点击右下角的Run按钮,执行相应的Java程序,就不会报OutOfMemoryError的错误了。
======================================================================================================
XML解析开发包:
1、JAXP:JAXP开发包是J2SE的一部分,它由javax.xml、org.w3c.dom、org.xml.sax包及其子包组成。
在javax.xml.parsers包中,定义了几个工厂类,程序员调用这些工厂类,可以得到XML文档的dom或sax的解析器,从而实现对XML文档的解析。
首先、创建工厂:
DocumentBuilderFactory factory = DocumentBuilderFactroy.newInstance();//因为DocumentBuilderFactory类是抽象类,不能new出它的对象只能调用它的静态方法获取它的对象。
其次、得到dom解析器:
DocumentBuilder builder = factory.newDocumentBuilder();
然后、加载XML文档,得到代表文档的Document对象:
Document document = builder.parse("*.xml");
拿到代表XML文档的document对象就可以操作XML文档中的各个节点了。
======================================================================================================
补充:
dom解析下,XML文档的每一个组成部分都会用一个对象表示,例如标签用Element,属性用Attribute,但不管什么对象,都是Node的子类,所以在开发中可以把获取到的任意节点都当作Node对待。
XML编程(CRUD)
create、read、update、delete
添加、查询、更新、删除;
除了这两种解析方法外,还有另外的解析方法。。。
======================================================================================================
在对XML文档进行添加、修改和删除操作时,不仅要更新document对象还要更新XML文档(把更新后的document对象重写到XML文档中)。
javax.xml.transform包中的Transformer类用于把代表XML文档的Document对象转换为某种格式后输出,例如把XML文档应用样式表后转换成一个HTML文档。利用这个对象,当然也可以把Document对象又重新写入到一个XML文档中。源和目的地。可以通过:
javax.xml.transform.dom.DOMSource类来关联要转换的document对象,
用javax.xml.transform.stream.StreamResult对象来表示数据的目的地。
Transformer对象通过TransformerFactory获得。
Transformer类通过transform方法完成转换操作,该方法接收个
(工厂对象(TransformerFactory)》》》转换器对象(Transformer)》》》转换方法(transform(DOMSource 源,StreamResult 目的地);))
======================================================================================================
SAX解析:
SAX解析采用事件处理的方式解析XML文件,利用SAX解析XML文档,涉及两个部分:解析器和事件处理器:
解析器可以使用JAXP的API创建,创建出SAX解析器后,就可以指定解析器去去解析某个XML文档。
解析器采用SAX方式在解析某个XML文档时,它只要解析到XML文档的一个指定部分,都会去调用事件处理器的一个方法,解析器在调用事件处理器的方法时,会把当前解析到的XML文件内容作为方法的参数传递给事件处理器。
事件处理器由程序员编写,程序员通过事件处理器中方法的参数,就可以很轻松的得到SAX解析器解析到的数据,从而可以决定如何对数据进行处理。
1、创建解析工厂;
SAXParserFactory fac = SAXParserFactory.newInstance();
2、获取解析器;
SAXParser sp = fac.newSAXParser();
3、得到读取器;
XMLReader re = sp.getXMLReader();
4、设置内容处理器;
re.setContentHandler(new ContentHandler(){ /*实现接口的代码块*/});
(或者:re.setContentHandler(new DefaultHandler());/*参数为DefaultHandler类的子类*/)
第一种方法是解析整个XML文档,第二种方法可以只解析某个标签;
其实还有一种内容处理器,也是先继承DefaultHandler类,然后把解析的内容封装到bean对象中。
5、读取XML文档内容;
re.parse("*.xml");
======================================================================================================
XML解析开发包:
2、dom4j:
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(new File());
OutputFormat format = OutputFormat.createPrettyPrint();//该对象标明格式按漂亮的格式进行输出;另外还有一个对象是按紧凑的格式进行输出;
format.setEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(),format);
xmlWriter.write(doc);//如果xmlWriter对象采用的流是字节流,那么该对象会先把doc对象按format对象给定的编码格式转换成字节,然后把数据交给字节流进行操作。
writer.close();//最后要关闭资源
======================================================================================================
XPath:
使用XPath可以快速定位到某个节点;
List list = document.selectNodes("//foo/bar");//获取foo节点下的所有bar节点;
Node node = document.selectSingleNode("//foo/bar");//获取foo节点下的第一个bar节点;
单斜杠是绝对路径即从根节点开始;
双斜杠是相对路径即从所有当前节点开始;
星号“*”表示选择所有由星号之前的路径所定位的元素;
例如:
/aa/bb/*表示选择所有路径依附于/aa/bb的元素;
/*/*/*/bbb表示选择所有的有3个祖先元素的bbb元素;
//bb[@*]表示选择有任意属性的bb元素;
//bb[not(@*)]表示选择没有属性的bb元素;
//bb[@id='b1']表示选择含有属性id='b1'的bb元素;

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better
