DOM解析xml文件

废话就不多说了,直接上代码,适合初学者(其实我就是刚学的)

import java.io.File;
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.NodeList;
import org.xml.sax.SAXException;

public class TestXml {
    public static void main(String[] args) {
        
        testDOM();
    }
    public static void testDOM(){
        File file = new File("d:/test01.xml");
        try {
            //定义工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);
            //其实上边就是准备工作,获取操作对象,没有为什么,就这样做(ps其实是我不懂,哈哈哈)
            NodeList list = doc.getElementsByTagName("value");
            for(int i=0;i<list.getLength();i++){//获取长度,遍历所有信息
                System.out.println("姓名:"+doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
                System.out.println("外号:"+doc.getElementsByTagName("secondname").item(i).getFirstChild().getNodeValue());
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

上边是Java的方法,很通俗易懂,估计看一遍就会了,下面是xml文件

<?xml version="1.0" encoding="UTF-8"?>
<result>
<value>
    <name>汉堡</name>
    <secondname>略略略</secondname>
</value>
<value>
    <name>浅浅</name>
    <secondname>略略略</secondname>
</value>
</result>

 上边的【NodeList list = doc.getElementsByTagName("value");】拿的就是这个xml文件的<value>,

同理,name和secondname也是拿的xml里面对应的值,写xml时注意写上<result>标签不然会报错(不太懂XML,反正不写就报错-- The markup in the document following the root element must be well-formed.org.xml.sax.SAXParseException,反正就是说你的格式不对)小小白就按照我这个写一遍应该就会了,对,就这样!^_^

 

转载于:https://my.oschina.net/u/3559788/blog/1537239

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值