Java解析XML(一) 使用DOM读取XML文件

2023-05-05 17:26:44 浏览数 (2)

DOM

DOM 是最容易使用的java XML解析器。它可以解析一个完整的XML文档并将其加载到内存中,然后用对象对其进行建模,以实现简单的node遍历。DMO是将XML直接加载到内存中进行处理的,所以不建议解析较大的XML文件。

读取XML文件

目标文件xmlDemo.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<note auth="Byron.y.y">
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

java代码使用dom4j解析XML文件

代码语言:javascript复制
package byron4j.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomDemo1 {
	public static void main(String[] args) throws Exception{
		
		String classPath = DomDemo1.class.getClass()
					.getResource("/").getPath();
		
		File file = new File(classPath);
		String fth = file.getParent();
		File fFile = new File(fth);
		String xmlPath = fFile.getParent()   "\src\xmlDemo.xml";
		
		
		File fXmlFile  = new File(xmlPath);
		
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);

		doc.getDocumentElement().normalize();

		System.out.println("Root element :"   doc.getDocumentElement().getNodeName());

		NodeList nList = doc.getElementsByTagName("note");

		System.out.println("----------------------------");

		for (int temp = 0; temp < nList.getLength(); temp  ) {

			Node nNode = nList.item(temp);

			System.out.println("nCurrent Element :"   nNode.getNodeName());

			if (nNode.getNodeType() == Node.ELEMENT_NODE) {

				Element eElement = (Element) nNode;
				System.out.println("author==> : "  eElement.getAttribute("auth"));
				System.out.println("1==> : "   eElement.getElementsByTagName("to").item(0).getTextContent());
				System.out.println("2==> : "   eElement.getElementsByTagName("from").item(0).getTextContent());
				System.out.println("3==> : "   eElement.getElementsByTagName("heading").item(0).getTextContent());
				System.out.println("4==> : "   eElement.getElementsByTagName("body").item(0).getTextContent());
				

			}
		}
	}
}

运行结果:

代码语言:javascript复制
Root element :note
----------------------------

Current Element :note
author==> : Byron.y.y
1==> : Tove
2==> : Jani
3==> : Reminder
4==> : Don't forget me this weekend!

0 人点赞