java读取xml文件

java中经常会读取一些配置信息,本文会说明java读取xml配置的例子:

text.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<menu1>
    <meun1name>菜单一</meun1name>
    <menuList>
        <menu2>
            <menu2Name>菜单2_1</menu2Name>
            <textField>name,age,sex</textField>
            <initClass>User</initClass>
        </menu2>
        <menu2>
            <menu2Name>菜单2_2</menu2Name>
            <textField>name1,age1,sex1</textField>
            <initClass>Teacher</initClass>
        </menu2>
    </menuList>
</menu1>

java中读取文件需要的是四个类主要:

Element
DocumentBuilder
DocumentBuilderFactory
Node

读取代码:

public static void main(String[] agrs){
        Element element = null;
        File f = new File("D:\\ideaWorkSpace\\tam\\src\\test\\java\\config.xml");
        DocumentBuilder db = null;
        DocumentBuilderFactory dbf = null;

        try {
            // 返回documentBuilderFactory对象
            dbf = DocumentBuilderFactory.newInstance();
            // 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
            db = dbf.newDocumentBuilder();
            // 得到一个DOM并返回给document对象
            Document dt = db.parse(f);
            // 得到一个elment根元素
            element = dt.getDocumentElement();

            System.out.println("根节点:"+element.getNodeName());

            NodeList nodeList = element.getChildNodes();
             }
        }catch (Exception e){
            e.printStackTrace();
        }

从开始到:

 // 得到一个elment根元素
 element = dt.getDocumentElement();

这句话结束,就可以得到所有xml信息。之后的处理围绕的是Node、NodeList来做就可以,但是需要注意的是,getChildNodes()会把空格和回车当做是一个节点,所以使用的时候应该加判断:

     NodeList nodeList = element.getChildNodes();
     for (int i = 0; i < nodeList.getLength(); i++){
         Node node1 = nodeList.item(i);
         if(node1  instanceof Element){
           if(node1.getNodeName().equals("meun1name")){
               System.out.println(node1.getTextContent());
           }
         }

    }

上面这些代码,就可以获取meun1name节点的属性值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值