XML初识(一)--使用DOM解析XML数据

    xiaoxiao2021-03-25  117

    XML是一种数据储存标准,可以在不同编程语言,不同程序和不同系统之间交换数据。 XML组织数据的形式是以倒排树的形式来存储的。即顶部是根节点,下面是子节点。

    下面给出一个简单的XML文件,然后使用DOM获取里面的内容。

    books.xml:

    下面是Demo:

    package com.imooc.domlearing; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DomParseXml { public static void main(String[] args) { //1.获取工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { //2.得到DocumentBuilder DocumentBuilder db = factory.newDocumentBuilder(); //3.根据文件名匹配文件,得到Document Document document = db.parse("books.xml"); //4.根据标签名字得到列表 NodeList list = document.getElementsByTagName("book"); System.out.println(list.getLength()); for(int i = 0;i<list.getLength();i++) { System.out.println("Now,we use "+(i+1)); //5.从list中取出两本书节点 Node node = list.item(i); //6.得到书的属性(即我们定义了一个id) NamedNodeMap nnm = node.getAttributes(); System.out.println("第"+i+"本书共有"+nnm.getLength()+"个属性"); //7.下面是遍历书属性的代码 for(int j = 0;j<nnm.getLength();j++) { Node attr = nnm.item(j); System.out.println("Attritube name : "+j+" " +attr.getNodeName()); System.out.println("Attritube value: "+j+" "+ attr.getNodeValue()); } //8.得到书的子节点 NodeList childlist = node.getChildNodes(); for(int k = 0;k<childlist.getLength();k++) { Node par = childlist.item(k); //9.这里要注意,xml节点的排列方式,换行也是一个节点。 if(par.getNodeType()==Node.ELEMENT_NODE) { System.out.println(par.getNodeName()+":"+par.getFirstChild().getNodeValue()); } } System.out.println("第"+i+"本书遍历完毕!!!"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

    下面是运行结果:

    2 Now,we use 10本书共有1个属性 Attritube name : 0 id Attritube value: 0 1 name:Linux Learning year:2001 author:Linus price:$490本书遍历完毕!!! Now,we use 21本书共有1个属性 Attritube name : 0 id Attritube value: 0 2 name:Git Learning year:1998 author:Linus price:$301本书遍历完毕!!!

    注意:我们这里改变books.xml文件的后缀名也是可以的,同样能够识别出来。不过我们需要保证文件内部是按照xml格式来组织的。

    转载请注明原文地址: https://ju.6miu.com/read-8190.html

    最新回复(0)