Java Xml 简明教程
Java DOM Parser - Query XML Document
Java DOM 解析器是 java 中的一个 API,用于解析和查询 XML 文稿。使用 Java DOM 解析器,我们可以查询大型 XML 文稿以深入了解我们的数据。手动检查整个 XML 文稿以获取相关信息并不容易。我们可以使用 getElementsByTagName() 方法按其标签名称来查询 XML 元素。若要基于属性值进行查询,可以使用 getAttribute() 方法。
Java DOM parser is an API in java to parse and query XML documents. Using Java DOM parser, we can query large XML documents to get insights about our data. Manually, it is not easy to check the entire XML document to obtain related information. We can query XML elements by their tag name using getElementsByTagName() method. To query based on attribute value, getAttribute() method can be used.
Query XML Using Java DOM Parser
我们可以使用以下步骤通过 DOM 解析器在 Java 中查询任何 XML 文稿:
We can query any XML document in Java using DOM parser through following steps −
-
*Step 1: *Creating a DocumentBuilder Object
-
*Step 2: *Reading the XML
-
*Step 3: *Parsing the XML Document
-
*Step 4: *Querying the XML Document
请参阅 this page 以了解前三个步骤。
Refer this page for first three steps.
Querying Elements by TagName
我们可以用 Document 接口上的 getElementsByTagName('carname') 方法通过标签名查询 XML 元素。此方法将采用 String 形式的标签名,并返回一个 NodeList,其中包含标签名相同的节点列表。
We can query the XML elements by their tag name by using the method, getElementsByTagName('carname') on the Document interface. This method takes tag name in the form of a String and returns the list of nodes with the same tag name as a NodeList.
Node 接口的 getTextContent() 方法采用 String 形式给出节点内部的文本内容。
The getTextContent() method of Node interface gives the text content inside the node in the form of a String.
cars.xml
cars.xml 文件在根元素 <cars> 内部有七个 <carname> 元素。
The cars.xml file has seven <carname> elements inside the root element, <cars>.
<?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>
Query XML Elements
在下面的程序中,我们已将所有节点获取到一个 nodeList 中,然后迭代每个节点以获取文本内容,并检查文本内容是否等于“Bentley 2”。如果找到,我们会在控制台上打印已找到;如果没有找到,我们会打印未找到。
In the following program, we got all the nodes into a nodeList and then iterated each node to get the text content and checked if that equals to "Bentley 2". If it is found, we are printing on the console that it is found or else we are printing not found.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.io.File;
public class QueryXMLDemo {
public static void main(String argv[]) {
try {
//Creating a DocumentBuilder Object
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Reading the XML file
File inputFile = new File("cars.xml");
//Parsing the XML Document
Document doc = dBuilder.parse(inputFile);
//checking "Bentley 2" car
int flag=0;
NodeList nList = doc.getElementsByTagName("carname");
for(int i=0;i<nList.getLength();i++) {
if(nList.item(i).getTextContent().equals("Bentley 2")) {
System.out.println("Bentley 2 car is "+"found");
flag=1;
break;
}
}
if(flag==0) {
System.out.println("Bentley 2 car is "+"not found");
}
} catch (Exception e) {e.printStackTrace();}
}
}
Querying Elements by Attributes
我们可以使用 Element 接口的 getAttribute("Attribute_name") 方法通过属性查询元素。此方法将采用属性名称作为参数,并返回属性值。
We can query the elements by their attributes using the method getAttribute("Attribute_name") of Element interface. This method takes attribute name as an argument and returns value of the attribute.
Example
在下面的程序中,我们已解析 cars.xml 文件,并且会在每次找到“Bentley”时增加计数变量。
In the following program, we have parsed cars.xml file and incremented the count variable every time "Bentley" is found.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.io.File;
public class QueryXMLAttributes {
public static void main(String argv[]) {
try {
//Creating a DocumentBuilder Object
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Reading the XML file
File inputFile = new File("cars.xml");
//Parsing the XML Document
Document doc = dBuilder.parse(inputFile);
//counting Bentley cars
int count=0;
NodeList nList = doc.getElementsByTagName("carname");
for(int i=0;i<nList.getLength();i++) {
Element ele = (Element) nList.item(i);
if(ele.getAttribute("company").equals("Bentley")) {
count++;
}
}
System.out.println("No of Bentley cars: "+ count);
} catch (Exception e) {e.printStackTrace();}
}
}