Java之读取XML文件内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82734936

下面是我的Persons.xml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<persons>
	<person id="0">
		<name>翠花</name>
		<age>18</age>
		<sex>女</sex>
	</person>
	<person id="1">
		<name>老王</name>
		<age>20</age>
		<sex>男</sex>
	</person>
</persons>

读取数据:

/**
 * 读取XML文件数据
 * @author 郑清
 */
public class GetXMLDataDemo {

	static File file = new File("E:/eclipse-workspace/JavaEE_workspace/Day34XML/src/Persons.xml");//Persons.xml文件绝对路径
	
	public static void main(String[] args) throws Exception {
		//①获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
		DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		//②获取一个与磁盘文件关联的非空Document对象
		Document doc = newDocumentBuilder.parse(file);
		//③通过文档对象获得该文档对象的根节点
		Element root = doc.getDocumentElement();
		
		//通过根节点获得子节点
		NodeList personList = root.getElementsByTagName("person");
		//System.out.println(personList);
		
		//这里获取第1个节点
		Node item = personList.item(0);
		System.out.println(item.getTextContent());//获取第一个节点的所有子节点值
		
		Element element = (Element)item;//这里转换成子类类型   ==》原因:父类没有对应的方法    这里只看类型不看值
		
		//这里获取第1个节点下 name节点值
		NodeList nameList = element.getElementsByTagName("name");
		System.out.println(nameList.item(0).getTextContent());
	}

}

运行结果图:

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82734936