java之xml解析

        项目里要用到xml解析,所以需要写一个java的xml解析工具类。因此特地去网上看了一下java,解析xml的例子,发现网上找到的大都只有代码例子,在实际的过程中也出了不少问题,所以想写一篇关于xml解析的基础文章,记录一下自已在学习过程中遇到的一些问题。

        DOM(文档对象模型)是HTML和XML文档的编程接口规范,与平台和语言无关,模型定义了HTML和XML在内存中的逻辑结构,提供了访问和存取HTML和XML文档的方法,可以说要自由的操纵XML文档就要用到DOM规范。

       解析XML的第一步是要获得一个文档解析器,将一个XML文档转化为一个DOM文档。Document接口描述了对应于整个XML的文档树,并提供了对数据的访问

                 // 先获取产生DocumentBuilder工厂

                //在通过这个工厂产生一个XML文档解析器(DocumentBuilder)

               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

               DocumentBuilder db = dbf.newDocumentBuilder();

               // 这个Document就是一个XML文件在内存中的镜像

               //把要解析的 XML 文档转化为输入流,以便 DOM 解析器解析它

             doc = db.parse(new File(xmlFile));

       在一个XML文档里只一个根元素,获取的方法为   Element element = doc.getDocumentElement();

       在XML中获取一个节点可以根据其节点的名称获取  

              NodeList nodeList = doc.getElementsByTagName(nodeName);

例如在这里获取node1里数据:
 

写道
public class OwnXmlReslove {

private Document doc = null;


   public void init(String filePath) throws Exception{
           File file = new File(filePath);
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = factory.newDocumentBuilder();
           doc = builder.parse(file);
      }

    public NodeList getHeadNode(String filePath,String nodeName) throws Exception{
            init(filePath);
            return doc.getElementsByTagName(nodeName);
     }

     public static void main(String[] args) {
         OwnXmlReslove xmlre = new OwnXmlReslove();
          try {
               NodeList nodelist =   xmlre.getHeadNode("D://PropertyRW/src/Wapper.xml", "classification");
              NodeList node = nodelist.item(0).getChildNodes();
              int length = node.getLength();
               for(int i = 0; i < length; i++){
                 Node no = node.item(i);
                      if(no instanceof Element){
                               System.out.println(no.getAttributes().getNamedItem("name").getNodeValue());
                               System.out.println(no.getAttributes().getNamedItem("ename").getNodeValue());
                               System.out.println(no.getAttributes().getNamedItem("id").getNodeValue());
                        }
                      }
             } catch (Exception e) {
                           e.printStackTrace();
                  }
    }
}

   这里的init()方法是获取一个xml解析器并把Document对象初始化。getHeadNode这个是因为在程序里会根据不同的名称获取不同的NodeList对象,所以我把它提取了出来。

   在main函数中 ,先获取标签名称为<classification>的文档对象,item(0)是获取集合的第一个对象。应该是要遍历获取但我这里在测试所以偷了一个小懒。再尝试获取<classification name="subject">的所有子节点。然后遍历他的所有子节点。然后判断node是否是一个元素节点,一个父节点的子节点可能有元素节点和文本节点等,这里我还不太清楚。除了元素节点和文本节点是否还有其他的节点。

 如果是元素节点那么通过getAttribute()方法获取当前节点的属性值,再根据名称的标签来获取元素的的值。如果需要获取node2节点里面的值那么还需要遍历一遍历node1节点,获取node1节点里的所有子节点,然后判断是否是元素节点,然后循环输出即可。

最后输出:

 

 

后来我在其他的文章里看到在循环遍历的时候有更好的写法,贴上来大家可以看下

写道
for(Node node=book.getFirstChild(); node != null; node=node.getNextSibling()) {
           if(node.getNodeType()==Node.ELEMENT_NODE) {
                     if(node.getNodeName().equals("name")) {
                                   String name=node.getNodeValue();
                                   String name1=node.getFirstChild().getNodeValue();
                                   System.out.println(name);
                                   System.out.println(name1);
                      }
                   if(node.getNodeName().equals("price")) {
                             String price=node.getFirstChild().getNodeValue();
                            System.out.println(price);
                   }
             }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值