java遍历读取xml文件内容
本文实例讲解了java遍历读取xml文件内容的详细代码,分享给大家供大家参考,具体内容如下
packagetest; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.OutputStream; importjava.util.Iterator; importjavax.xml.namespace.NamespaceContext; importjavax.xml.namespace.QName; importjavax.xml.stream.XMLInputFactory; importjavax.xml.stream.XMLOutputFactory; importjavax.xml.stream.XMLStreamException; importjavax.xml.stream.XMLStreamReader; importjavax.xml.stream.XMLStreamWriter; importorg.apache.axiom.om.OMAbstractFactory; importorg.apache.axiom.om.OMAttribute; importorg.apache.axiom.om.OMComment; importorg.apache.axiom.om.OMContainer; importorg.apache.axiom.om.OMDataSource; importorg.apache.axiom.om.OMDocType; importorg.apache.axiom.om.OMDocument; importorg.apache.axiom.om.OMElement; importorg.apache.axiom.om.OMException; importorg.apache.axiom.om.OMFactory; importorg.apache.axiom.om.OMNamespace; importorg.apache.axiom.om.OMProcessingInstruction; importorg.apache.axiom.om.OMSourcedElement; importorg.apache.axiom.om.OMText; importorg.apache.axiom.om.OMXMLParserWrapper; importorg.apache.axiom.om.impl.builder.StAXOMBuilder; importorg.xml.sax.helpers.XMLReaderFactory; publicclassAxiomtest{ publicstaticvoidmain(String[]args)throwsFileNotFoundException,Throwable{ //readxml FileInputStreamxmlFile=newFileInputStream("line-item2.xml"); XMLStreamReaderparser=XMLInputFactory.newInstance().createXMLStreamReader(xmlFile); //还需要StAXOMBuilder对象 StAXOMBuilderbuilder=newStAXOMBuilder(parser); OMElementdoc=builder.getDocumentElement();//读到<fool></fool> OMElementcre=doc.getFirstChildWithName(newQName("student"));//读到<student> OMElementcre1=cre.getFirstChildWithName(newQName("id"));//读到<id></id> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1=cre.getFirstChildWithName(newQName("name"));//读到<name></name> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1=cre.getFirstChildWithName(newQName("age"));//读到<age></age> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1=cre.getFirstChildWithName(newQName("sex"));//读到<sex></sex> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1=cre.getFirstChildWithName(newQName("message"));//读到<sex></sex> System.out.println(cre1.getLocalName()+":"+cre1.getText()); System.out.println("------------------------------1"); Iterator<OMElement>iter=doc.getChildElements(); while(iter.hasNext()){ OMElementtemp=iter.next(); System.out.println("===================="); System.out.println(temp.getLocalName()); //System.out.println(temp.getText()); if(temp.getLocalName().equals("student")){ Iterator<OMElement>iter1=temp.getChildElements(); System.out.println("----------------"); while(iter1.hasNext()){ OMElementtemp1=iter1.next(); System.out.println(temp1.getLocalName()+":"+temp1.getText()); } } } System.out.println("!!!!!!!!!!!!!"); FileInputStreamfile=newFileInputStream("line-item2.xml"); XMLStreamReaderread=XMLInputFactory.newInstance().createXMLStreamReader(file); StAXOMBuildersta=newStAXOMBuilder(read); OMElementall=sta.getDocumentElement(); Iterator<OMElement>ite1=all.getChildElements(); while(ite1.hasNext()){ OMElementtemp=ite1.next(); if(temp.getLocalName().equals("student")){ Iterator<OMElement>ite2=temp.getChildElements(); while(ite2.hasNext()){ OMElementtemp1=ite2.next(); System.out.println(temp1.getLocalName()+":"+temp1.getText()); } } } //writexml OMFactoryfactory=OMAbstractFactory.getOMFactory(); //建立doc节点,doc节点会和下面的root节点合并 OMDocumentdod=factory.createOMDocument(); //建立root节点 OMElementroot=factory.createOMElement("root","",""); OMElementadd=factory.createOMElement("dabi","",""); //建立两个普通节点 OMElementstu=factory.createOMElement("student","",""); stu.addChild(factory.createOMText("mac")); OMElementtea=factory.createOMElement("teacher","",""); tea.addChild(factory.createOMText("silly")); //构建树,将两个普通节点连到root节点上 root.addChild(stu); root.addChild(tea); //构建树,将root节点连到doc节点上 dod.addChild(root); //构建writer做输出器 XMLStreamWriterwriter=XMLOutputFactory.newInstance().createXMLStreamWriter( newFileOutputStream("2.xml")); root.serialize(writer);//cacheon writer.flush(); FileInputStreamxmlFile1=newFileInputStream("2.xml"); XMLStreamReaderparser1=XMLInputFactory.newInstance().createXMLStreamReader(xmlFile1); StAXOMBuilderbuilder1=newStAXOMBuilder(parser1); OMElementdoc1=builder1.getDocumentElement(); Iterator<OMElement>iter1=doc1.getChildElements(); while(iter1.hasNext()){ OMElementtemp=iter1.next(); System.out.println("===================="); System.out.println(temp.getLocalName()+":"+temp.getText()); } System.out.println("!!!!!!!!"); OMFactoryomf=OMAbstractFactory.getOMFactory(); //OMDocumentod=omf.createOMDocument(); OMElementroot1=omf.createOMElement("root","",""); OMElementname=omf.createOMElement("name","",""); OMElementsex=omf.createOMElement("sexy","",""); sex.addChild(omf.createOMText("man")); name.addChild(omf.createOMText("dabi")); root1.addChild(sex); root1.addChild(name); //od.addChild(root1); XMLStreamWriterxmlw=XMLOutputFactory.newInstance().createXMLStreamWriter(newFileOutputStream("3.xml")); root1.serialize(xmlw); xmlw.flush(); } }
<?xmlversion="1.0"encoding="UTF-8"?> <fool> <student> <name>mac</name> <id>12</id> <age>33</age> <sex>male</sex> <message>helloworld</message> </student> <student> <name>silly</name> <id>5</id> <age>12</age> <sex>female</sex> </student> <teacher> <name>Mr.Jones</name> <id>2</id> <age>31</age> <sex>male</sex> </teacher> <student> <name>macy</name> <id>2</id> <age>40</age> <sex>female</sex> </student> <student> <name>tom</name> <id>32</id> <age>31</age> <sex>male</sex> </student> <message>helloworld</message> </fool>
再分享一例:用JAVA读取XML文件
解析XML的步骤如下:
- 1.创建DocumentBuilder工厂
- 2.创建DocumentBuilder对象
- 3.DocumentBuilder对象的parse方法得到Document对象
- 4.Document对象的getElementsByTagName得到NodeList集合
- 5.通过getFirstChild和getNextSibling进行遍历
用到的包:
- importjavax.xml.parsers.*;
- importorg.w3c.dom.*;
- importorg.xml.sax.*;
用到的对象:
- DocumentBuilderFactory:创建DocumentBuilder的抽象工厂
- DocumentBuilder:可以从XML获取一个Document
- Document:提供供对文档数据的基本访问
用到的方法:
- DocumentBuilder.parse(String)':将给定URI的内容解析为一个XML文档,并且返回一个新的DOMDocument对象
- Document.getElementsByTagName(String)':返回具有给定标记名称的所有Element的NodeList
- Element.getAttribute(String)':通过名称获得属性值
下面来解析一个XML文件
importjavax.xml.parsers.*; importorg.w3c.dom.*; importorg.xml.sax.*; publicclassTest { publicstaticvoidmain(String[]args) { DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance(); try { DocumentBuilderdb=dbf.newDocumentBuilder(); Documentdoc=db.parse("pet2.xml"); NodeListdogList=doc.getElementsByTagName("dog"); System.out.println("共有"+dogList.getLength()+"个dog节点"); for(inti=0;i<dogList.getLength();i++) { Nodedog=dogList.item(i); Elementelem=(Element)dog; System.out.println("id:"+elem.getAttribute("id")); for(Nodenode=dog.getFirstChild();node!=null;node=node.getNextSibling()) { if(node.getNodeType()==Node.ELEMENT_NODE) { Stringname=node.getNodeName(); Stringvalue=node.getFirstChild().getNodeValue(); System.out.print(name+":"+value+"\t"); } } System.out.println(); } } catch(Exceptione) { e.printStackTrace(); } } }
XML文件
<pets> <dogs> <dogid="1"> <name>YAYA</name> <health>100</health> <love>0</love> <strain>酷酷的雪娜瑞</strain> </dog> <dogid="2"> <name>OUOU</name> <health>90</health> <love>15</love> <strain>聪明的拉布拉多犬</strain> </dog> </dogs> <penguins> <penguinid="3"> <name>QQ</name> <health>100</health> <love>20</love> <sex>Q仔</sex> </penguin> </penguins> </pets>
以上就是本文的全部内容,希望对大家的学习有所帮助。