dom解析xml示例

dom.xml


 

  textnode1ATEXTnode2
	111
    text3
  
  B
    222
  
  
    C
    333
  
  
	textnode4
  

package com.log.client;


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 U8ProfilterMain {

	public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
        	//加载文件
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document d = builder.parse("file:///D:\\ProgramData\\workspace_git\\git\\我的资料\\U8\\20230203-sql解析\\demo.xml");
            
            //获取标签属性
            NodeList nodeList = d.getElementsByTagName("world");
            System.out.println("标签的个数:"+nodeList.getLength());
            
            //便利
            for (int i = 0; i 判断是否是[Element元素节点]:" + (node.getNodeType() == Node.ELEMENT_NODE));
            	
            	//转化为element
            	Element element = (Element) node;
				System.out.println("节点名称: " + element.getNodeName() + ", 属性id值:" + element.getAttribute("id"));
				
				//获取子节点
				NodeList chs = node.getChildNodes();//备注:子节点之间的空白,换行,回车都是一个节点
				for(int j = 0; j < chs.getLength(); j++) {
					Node chnode = chs.item(j);
					System.out.print(j + ":节点类型[" + chnode.getNodeType() + "],");
					
					if(chnode.getNodeType() == Node.TEXT_NODE) {
						//文本节点: 如子节点之间的空白,换行,回车,以及文本内容
						System.out.println("文本节点,当前值为["+chnode.getNodeValue()+"]");
					}else if(chnode.getNodeType() == Node.ELEMENT_NODE) {
						//元素节点
						System.out.println("元素节点,当前值为["+chnode.getNodeName()+"]");
						
						if("name".equals(chnode.getNodeName())) {
							Element nameElement = (Element) chnode;
							System.out.println("      name="+nameElement.getTextContent() + ", _type=type"+nameElement.getAttribute("type"));
						}else  if("size".equals(chnode.getNodeName())) {
							Element sizeElement = (Element) chnode;
							System.out.println("      size="+sizeElement.getTextContent());
						}
					}
				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
		

	}
	

}

你可能感兴趣的:(dom,java,开发语言)