java读取xml

解析xml的步骤

  • 创建DocumentBuilder工厂
  • 创建DocumentBuilder对象
  • DocumentBuilder对象的parse方法得到Document对象
  • Document对象的getElementsByTagName得到NodeList集合
  • 通过getFirstChild和getNextSibling进行遍历

用到的包

  import javax.xml.parsers.*;
  import org.w3c.dom.*;
  import org.xml.sax.*;

需要的对象

  • DocumentBuilderFactory:创建DocumentBuilder的抽象工厂
  • DocumentBuilder:可以从 XML 获取一个 Document
  • Document:提供供对文档数据的基本访问

xml文件内容

  <?xml version="1.0" encoding="utf-8"?>
    <users>
      <user id="1">
        <username>root</username>
        <password>123456</password>
      </user id="2">
        <username>ordinay</username>
        <password>1111111</password>
      </user>
    </users>
  import javax.xml.parsers.*;
  import org.w3c.dom.*;
  import org.xml.sax.*;

  public class ReadXml{
    public static void main (String[]args){
      //create a abstract factory
      DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

      try{
        DocumentBuilder db = dbf.newDocumentBuilder();
        //Gets a DOM object and returns it to the document object
        Document doc = db.parse("xml文件的路径");
        //Gets a list of root elements
        NodeList userList = doc.getElementsByTagName("user");
        //Traversal root element
        System.out.println("共有 "+userList.getLength()+" 个user节点");

        for(int i = 0; i < userList.getLength(); i ++){
          Node user = userList.item(i);  
          Element elem = (Element) user;
          //Traversal root element sub node
          System.out.println("id:" + elem.getAttribute("id"));  
          for(Node node = user.getFirstChild();node != null; node = node.getNextSibling()){
            if (node.getNodeType() == Node.ELEMENT_NODE)  
            {  
                String name = node.getNodeName();  
                String value = node.getFirstChild().getNodeValue();  
                System.out.print(name + ":" + value + "\t");  
            }
            System.out.println();
          }
        }
      }
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值