java程序操作xml文件

1 篇文章 0 订阅

java代码

package xmlTest;

import javax.lang.model.element.Element;

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

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

public class XmlTest2 {
	
	public static void main(String[] args){
		//文件路径
		String filePath="/Users/apple/Downloads/dom4j-1.6.1/project.xml";
		DocumentBuilderFactory documentBuliderFactory=DocumentBuilderFactory.newInstance();
		
		try {
			DocumentBuilder documentBuilder=documentBuliderFactory.newDocumentBuilder();
			Document document=documentBuilder.parse(new java.io.File(filePath));
			NodeList nodeList=document.getElementsByTagName("dog");
			System.out.println(nodeList.getLength());
            for (int i = 0; i < nodeList.getLength(); i++)  
            {  
                Node dog = nodeList.item(i);  
                
                //输出dog节点的第一个属性(笔者实现的时候不能同dog.getAttribute(),因此只能用这种方式)
                System.out.println(dog.getAttributes().item(0));
                for (Node node = dog.getFirstChild(); node != null; node = node.getNextSibling())  
                {  
                    if (node.getNodeType() == Node.ELEMENT_NODE)  
                    {  
                        String name = node.getNodeName();
                        //文本实质上是node的子节点
                        String value = node.getFirstChild().getNodeValue();  
                        System.out.print(name + ":" + value + "\t");  
                    }  
                }  
                System.out.println();  
            }  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<pets>  
    <dogs>  
        <dog id="1">            
            <name>YAYA</name>  
            <health>100</health>  
            <love>0</love>  
            <strain>酷酷的雪娜瑞</strain>  
        </dog>  
        <dog id="2">            
            <name>OUOU</name>  
            <health>90</health>  
            <love>15</love>  
            <strain>聪明的拉布拉多犬</strain>  
        </dog>  
    </dogs>  
    <penguins>  
        <penguin id="3">            
            <name>QQ</name>  
            <health>100</health>  
            <love>20</love>  
            <sex>Q仔</sex>             
        </penguin>          
    </penguins>  
</pets>  

运行结果:

2

id="1"

name:YAYA health:100 love:0 strain:酷酷的雪娜瑞

id="2"

name:OUOU health:90 love:15 strain:聪明的拉布拉多犬


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值