Java Xml 简明教程
Java SAX Parser - Query XML Document
Java SAX Parser 是 java 中的 API,可用于查询 XML 文档。要使用基于事件的 API 查询大型 XML 文档,我们可以使用 Java SAX parser API。SAXParser API 存在于 javax.xml.parsers 包内。我们可以通过继承 ContentHandler 接口的反过来继承 DefaultHandler 类的 Handler 类中的回调方法来查询任何 XML 文档。
Java SAX Parser is an API in java which can be used to query XML documents. To query large XML documents using event based APIs, we can use Java SAX parser API. The SAXParser API is present inside the javax.xml.parsers package. We can query any XML document by implementing the call back methods inside Handler class by inheriting DefaultHandler class which in turn inherits ContentHandler interface.
Query XML using Java SAX parser
我们可以通过以下步骤使用 SAX parser 在 Java 中查询任何 XML 文档 -
We can query any XML document in Java using SAX parser through following steps −
-
*Step 1: *Implementing a Handler class
-
*Step 2: *Creating a SAXParser Object
-
*Step 3: *Reading the XML
-
*Step 4: *Creating object for Handler class
-
*Step 5: *Parsing the XML Document
-
*Step 6: *Querying the Elements
有关前五个步骤,请参考 this chapter 。
Refer this chapter for the first five steps.
Step 6: Querying the Elements
ContenHnadler 和 Attributes 接口提供了各种帮助我们查询元素及其属性的方法。为了查询所需信息,我们在 Handler 类内部实现了代码。
The ContenHnadler and Attributes interfaces provide various methods which help us query elements and their attributes. For querying required information, We implement code inside our Handler class.
Querying Elements by TextContent
characters() 方法用于获取元素的内容。 endDocument() 函数在文档结尾处调用。我们可以使用此方法在关闭 XML 文件之前执行一些我们需要的必要操作。
The characters() method is used to get the content of elements. The endDocument() function is called at the end of the document. We can use this method to perform some necessary actions that we need to do before closing our XML file.
Example
我们需要查询以下 cars.xml 文件以找出文档中是否存在“宾利 2”汽车。
We need to query the following cars.xml file to find out whether there is "Bentley 2" car in the document.
<?xml version = "1.0"?>
<cars>
<carname company="Ferrari" >Ferrari 101</carname>
<carname company="Lamborghini">Lamborghini 001</carname>
<carname company="Lamborghini">Lamborghini 002</carname>
<carname company="Lamborghini">Lamborghini 003</carname>
<carname company="Bentley">Bentley 1</carname>
<carname company="Bentley">Bentley 2</carname>
<carname company="Bentley">Bentley 3</carname>
</cars>
在以下 Java 程序中,我们在 UserHandler 类中实现了 characters() 和 endDocument() 方法。我们已经编写了代码以在 characters() 函数中查找宾利汽车,并在 endDocument() 方法中打印最终结果。
In the following java program, we have implemented characters() and endDocument() methods inside UserHandler class. We have written the code to find Bentley cars inside the characters() function and the end result is printed using endDocument() method.
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
//Implementing UserHandler Class
class UserHandler extends DefaultHandler {
boolean found = false;
public void characters(char[] ch, int start, int length) throws SAXException{
String textContent = new String(ch,start,length);
if(textContent.equals("Bentley 2")) {
found=true;
}
}
public void endDocument() {
if(found)
System.out.println("Bentley 2 car is found");
else
System.out.println("Bentley 2 car is not Found");
}
}
public class QueryXMLElements {
public static void main(String args[]) {
try {
//Creating a DocumentBuilder Object
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Reading the XML
File xmlFile = new File("cars.xml");
//Creating UserHandler object
UserHandler userHandler = new UserHandler();
//Parsing the XML Document
saxParser.parse(xmlFile, userHandler);
} catch(Exception e) {
e.printStackTrace();
}
}
}
输出显示已发现宾利汽车。
The output displays that the Bentley car is found.
Bentley 2 car is found
Querying Elements by Attributes
我们可以使用 Attributes 接口通过其属性查询元素。我们从 startElement() 函数中将元素的属性列表作为最后一个参数获取。如前一章所述, getValue("attr_name") 函数用于获取属性值。
We can query the elements by their attributes using the Attributes interface. We get the list of attributes of an element as a last argument from the startElement() function. As discussed in the previous chapter, the getValue("attr_name") function is used to obtain the attribute value.
Example
让我们使用我们在前一个示例中使用的 cars.xml 文件来计算宾利汽车的数量。此信息只能通过属性值获取。当解析器遇到元素时,我们使用 getValue("company") 获取公司属性并在该公司为宾利时增加计数。
Let us use our cars.xml file that we used in the previous example to count number of Bentley cars. This information can be obtained only through the attribute value. As the parser encounters an element, we are using getValue("company") to get the company attribute and incrementing the count if that company is Bentley.
import java.io.File;
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;
//Implementing UserHandler Class
class UserHandler extends DefaultHandler {
int count=0;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String company = attributes.getValue("company");
if(qName.equals("carname") && company.equals("Bentley")) {
count++;
}
}
public void endDocument() {
System.out.println("No. of Bentley cars found : " + count);
}
}
public class QueryXMLAttributes {
public static void main(String args[]) {
try {
//Creating a DocumentBuilder Object
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Reading the XML
File xmlFile = new File("cars.xml");
//Creating UserHandler object
UserHandler userHandler = new UserHandler();
//Parsing the XML Document
saxParser.parse(xmlFile, userHandler);
} catch(Exception e) {
e.printStackTrace();
}
}
}
当调用 endDocument() 方法时显示输出。
The output is displayed when the endDocument() method is invoked.
No.of Bentley cars found : 3