欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DOM解析XML文件

程序员文章站 2022-05-29 08:20:53
...
public class DomParseXml {

	public static void main(String[] args) {

		// 获得解析器工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		// 获得解析器
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			// 加载文件,转换成Document
			Document doc = builder.parse("studentinfo.xml");

			// 解析
			NodeList stulist = doc.getElementsByTagName("stu");
			System.out.println("一共有:" + stulist.getLength() + "个节点");
			for (int i = 0; i < stulist.getLength(); i++) {
				Node stu = stulist.item(i);
				
				// 获得stu节点下的子节点
				NodeList childList = stu.getChildNodes();
				for (int j = 0; j < childList.getLength(); j++) {
					if (childList.item(j).getNodeType() == Node.ELEMENT_NODE) {
						System.out.println("节点名称:" + childList.item(j).getNodeName());
						System.out.println("节点的值:" + childList.item(j).getFirstChild().getNodeValue());
						System.out.println("---------------------------");
					}