Java Xml 简明教程
Java DOM4J Parser - Query XML Document
Java DOM4J解析器是一个开源Java库,可用于解析和查询XML文档中的必要信息。我们可以使用DOM4J的Document 和Element接口的方法查询XML文档。elements() 方法检索根元素的所有元素。使用attributeValue()方法,我们可以查询元素的属性。
Java DOM4J parser is an open source Java library to parse and query the necessary information from XML documents. We can query XML documents using the methods of Document and Element interfaces of DOM4J. The elements() method retrieves all the elements of root element. Using attributeValue() method, we can query the attributes of elements.
Query XML Using Java DOM4J Parser
以下是在使用Java DOM4J解析器查询文档时使用的步骤:
Following are the steps used while querying a document using Java DOM4J Parser −
-
*Step 1: *Creating SAXReader object
-
*Step 2: *Reading the XML file
-
*Step 3: *Parsing the XML
-
*Step 4: *Extracting the root
-
*Step 5: *Querying the Document
有关前四个步骤,请参阅本部分的 Parse XML Document 章。
Refer Parse XML Document chapter of this section for first four steps.
Querying Elements
要使用特定名称获取元素,我们可以使用Element接口的 elements() 方法,并以字符串的形式将我们获取元素名称作为参数传递。此方法返回具有相同名称的元素列表。
To get elements with specific name, we can use elements() method of Element interface and pass the name of the element we need to obtain as a parameter in the form of a string. This method returns the list of elements with the same name.
Element接口的 getData() 方法以字符串形式返回文本数据。为了根据文本内容查询元素,我们可以将此方法与equals()方法一起用于比较。
The getData() method of Element interface returns the text data in the form of a String. To query an element based on its text content, we can use this method with equals() method for comparison.
Example
以下是用于查询的 cars.xml 文件:
Following is the cars.xml file we need to query −
<?xml version = "1.0"?>
<cars>
<carname company="Ferarri" >Ferarri 101</carname>
<carname company="Lamborgini">Lamborgini 001</carname>
<carname company="Lamborgini">Lamborgini 002</carname>
<carname company="Lamborgini">Lamborgini 003</carname>
<carname company="Bentley">Bentley 1</carname>
<carname company="Bentley">Bentley 2</carname>
<carname company="Bentley">Bentley 3</carname>
</cars>
使用 QueryElements.java 程序,我们正在查询 cars.xml 文件,以查找是否存在“宾利 2”汽车。我们从 elements() 方法获取所有“carname”元素,并使用 getData() 方法比较文本内容。
Using the QueryElements.java program, we are querying the cars.xml file to find if there is "Bentley 2" car available. We get all the 'carname' elements from elements() method and comparing the text content using getData() method.
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class QueryElements {
public static void main(String[] args) {
try {
//Creating SAXReader
SAXReader reader = new SAXReader();
//Reading the XML file
File inputFile = new File("cars.xml");
//Parsing the XML
Document document = reader.read(inputFile);
//Extracting the root
Element RootElement = document.getRootElement();
List<Element> elements = RootElement.elements("carname");
boolean found = false;
//Iterating over the List
for (Element ele : elements) {
if(ele.getData().equals("Bentley 2")) {
found = true;
}
}
if(found) {
System.out.println("Bentley 2 car is found");
}
else {
System.out.println("Bentley 2 car is not found");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Querying Attributes
我们可以使用 attributeValue() 方法查询 Element 接口的特定属性。我们可以传递一个字符串值作为此方法的参数,该字符串值是该属性的名称,它将该值作为字符串返回。
We can query for a specific attribute of an Element interface by using the attributeValue() method. We can pass a string value which is the name of the attribute as an argument to this method and it returns the value as a string.
Example 1
以下 QueryAttributes.java 程序获取“carname”元素列表,并检查其属性“company”的值是否等于“Bentley”,整数变量“count”增量。
The following QueryAttributes.java program gets the list of 'carname' elements and checks if the value of its attribute 'company' equals to 'Bentley' and the integer variable 'count' is incremented.
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class QueryAttributes {
public static void main(String[] args) {
try {
//Creating SAXReader
SAXReader reader = new SAXReader();
//Reading the XML file
File inputFile = new File("cars.xml");
//Parsing the XML
Document document = reader.read(inputFile);
//Extracting the root
Element RootElement = document.getRootElement();
List<Element> elements = RootElement.elements("carname");
int count = 0;
for (Element ele : elements) {
if(ele.attributeValue("company").equals("Bentley"))
count++;
}
System.out.println("No of Bentley cars found: " + count);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
Output
输出窗口显示文档中找到的宾利汽车数量。
The output window displays the number of Bentley cars found in the document.
No of Bentley cars found: 3
Example 2
考虑根元素“class”内的以下 studentData.xml 文件,其中包含三个 student 元素。现在尝试打印学号为 493 的学生信息。
Consider the following studentData.xml file with three student elements inside the root element 'class'. Let us now try to print the information about the student with roll number 493.
<?xml version = "1.0"?>
<class>
<student rollno = "393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
以下 QueryStudent.java 程序获取根元素“class”的所有元素。它比较学号属性的值与“493”。如果匹配,则将使用 elementText() 方法打印所有学生详细信息。
The following QueryStudent.java program gets all the elements of the root element 'class'. It the compares the value of roll number attribute with '493'. If it matches, it prints all the student details using elementText() method.
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class QueryStudent {
public static void main(String[] args) {
try {
//Creating SAXReader
SAXReader reader = new SAXReader();
//Reading the XML file
File inputFile = new File("studentData.txt");
//Parsing the XML
Document document = reader.read(inputFile);
//Extracting the root
Element RootElement = document.getRootElement();
System.out.println("Root element :" + RootElement.getName());
List<Element> elements = RootElement.elements();
System.out.println("----------------------------");
for (Element ele : elements) {
if(ele.attributeValue("rollno").equals("493")) {
System.out.println("\nCurrent Element :"
+ ele.getName());
System.out.println("Student roll no : "
+ ele.attributeValue("rollno") );
System.out.println("First Name : "
+ ele.elementText("firstname"));
System.out.println("Last Name : "
+ ele.elementText("lastname"));
System.out.println("First Name : "
+ ele.elementText("nickname"));
System.out.println("Marks : "
+ ele.elementText("marks"));
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}