加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml dom解析器 遍历打印标签

发布时间:2020-12-16 05:29:10 所属栏目:百科 来源:网络整理
导读:package com.lan.xml;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.El
package com.lan.xml;

import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;



public class Demo2 {
	public static void main(String[] args) {
		//1.创建工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		//2.得到dom解析器
		DocumentBuilder builder = null;
		try {
			 builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		//3.解析xml文档,得到代表文档的document
		try {
			Document document = builder.parse("src/book.xml");
			
			NodeList nlist = document.getElementsByTagName("书名");
			
			Node bookname = nlist.item(0);
			
			String content = bookname.getTextContent();
			
			
			
			System.out.println(content);
			System.out.println();
			
			//强行转换Element(前提是知道获取的Node为Element
			Element bookNameChange = (Element) nlist.item(0);
			String value = bookNameChange.getAttribute("name");
			System.out.println(value);
			System.out.println();
			
			
			//递归遍历打印标签
			
			//得到根结点
			Node root = document.getElementsByTagName("书架").item(0);
			
			list(root);
			
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
//递归遍历打印标签
	private static void list(Node root) {
		if (root instanceof Element) {
			System.out.println(root.getNodeName());
		}
		//System.out.println(root.getNodeName());
	
		NodeList list = root.getChildNodes();
		
		for(int i=0;i<list.getLength();i++){
			Node Child = list.item(i);
			list(Child);
		}
	}
}



<?xml version="1.0" encoding="UTF-8" ?>
<书架>
	<书>
		<书名 name="xxxxx">lan</书名>
		<作者>lan</作者>
		<售价>100000000000000000元</售价>
	</书>
</书架>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读