Java Reading XML using DOM parser

本文介绍如何使用Java的DOM解析器读取并解析XML文件。通过具体示例展示了如何获取XML文档的根元素、遍历所有带有特定标签名的节点,并提取所需的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Document, Element and Attr Interface ALL extend from Node Interface.

The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.

The Element interface represents an element in an HTML or XML document. Elements may have attributes associated with them;


book.xml - the XML file to be read

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book>
		<title>DST</title>
		<publisher>ORiley</publisher>
		<price>10.00</price>
	</book>
	<book>
		<title>News</title>
		<publisher>NYT</publisher>
		<price>12.00</price>
	</book>
</bookstore>

ReadXML.java - reads book.xml

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

import java.io.File;

public class ReadXML {

	public static void main(String[] args) {
		try {
			File fXmlFile = new File("book.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();

			// get root element
			System.out.println("Root element : "
					+ doc.getDocumentElement().getNodeName());
			
			// node list with tag ame "book"
			NodeList nList = doc.getElementsByTagName("book");

			for (int i = 0; i < nList.getLength(); i++) {
				// get a node from node list
				Node node = nList.item(i);

				// if the node is an element, print its title, publisher, price
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) node;

					System.out.println("title: "
							+ getTagValue("title", eElement));
					System.out.println("publisher: "
							+ getTagValue("publisher", eElement));
					System.out.println("price: "
							+ getTagValue("price", eElement));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// read the tag value from an Element
	private static String getTagValue(String tag, Element elem) {
		NodeList nList = elem.getElementsByTagName(tag).item(0).getChildNodes();
		Node nValue = (Node) nList.item(0);
		return nValue.getNodeValue();

	}
}

Reference:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Node.html

http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Element.html

http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Document.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值