java读取xml

package org.showxml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class JavaReadXml {
  // Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对  
  // 内存的操作来实现对XML的操作,首先第一步获取XML相关的Document  
  private Document doc = null;  
  
  public void init(String xmlFile) throws Exception {  
  // 很明显该类是一个单例,先获取产生DocumentBuilder工厂  
  // 的工厂,在通过这个工厂产生一个DocumentBuilder,  
  // DocumentBuilder就是用来产生Document的  
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  DocumentBuilder db = dbf.newDocumentBuilder();  
  // 这个Document就是一个XML文件在内存中的镜像  
  doc = db.parse(new File(xmlFile));  
  }  
  
  // 该方法负责把XML文件的内容显示出来  
  public void viewXML(String xmlFile) throws Exception {  
  this.init(xmlFile);  
  // 在xml文件里,只有一个根元素,先把根元素拿出来看看  
  Element element = doc.getDocumentElement();  
  System.out.println("根元素为:" + element.getTagName());  
  
  NodeList nodeList = doc.getElementsByTagName("person");  
  System.out.println("book节点链的长度:" + nodeList.getLength());  
  
  Node fatherNode = nodeList.item(0);  
  System.out.println("父节点为:" + fatherNode.getNodeName());  
  
  // 把父节点的属性拿出来  
  NamedNodeMap attributes = fatherNode.getAttributes();  
  
  for (int i = 0; i < attributes.getLength(); i++) {  
  Node attribute = attributes.item(i);  
  System.out.println("book的属性名为:" + attribute.getNodeName()  
  + " 相对应的属性值为:" + attribute.getNodeValue());  
  }  
  
  NodeList childNodes = fatherNode.getChildNodes();  
  System.out.println(childNodes.getLength());  
  for (int j = 0; j < childNodes.getLength(); j++) {  
  Node childNode = childNodes.item(j);  
  // 如果这个节点属于Element ,再进行取值  
  if (childNode instanceof Element) {  
  // System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());  
  System.out.println("子节点名为:" + childNode.getNodeName()  
  + "相对应的值为" + childNode.getFirstChild().getNodeValue());  
  }  
  }  
  }  
  
  public static void main(String[] args) throws Exception {  
  JavaReadXml parse = new JavaReadXml();  
  
  // 我的XML文件  
  parse.viewXML("person.xml");  
  }  
 
}  



<?xml version="1.0" encoding="UTF-8"?>  
<book>
<person>  
<first>wang</first>  
<last>laohu</last>  
<age>25</age>  
<version>中国邮电出版社</version>  
</person>  
<person>  
<first>li</first>  
<last>junjia</last>  
<age>24</age>  
<version>清华大学出版社</version>  
</person>
</book> 






package org.showxml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class ReadXml {

   
     public ReadXml() {
            //(1)得到DOM解析器的工厂实例
            DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
            //得到javax.xml.parsers.DocumentBuilderFactory;类的实例就是我们要的解析器工厂
            try  {
                //(2)从DOM工厂获得DOM解析器
                DocumentBuilder dombuilder=domfac.newDocumentBuilder();
                //通过javax.xml.parsers.DocumentBuilderFactory实例的静态方法newDocumentBuilder()得到DOM解析器
                //(3)把要解析的XML文档转化为输入流,以便DOM解析器解析它
                InputStream is=new FileInputStream("/home/core/Workspace/ShowXml/Books.xml");  //xml 的路径         
                //(4)解析XML文档的输入流,得到一个Document
                Document doc=dombuilder.parse(is);
                //由XML文档的输入流得到一个org.w3c.dom.Document对象,以后的处理都是对Document对象进行的
                //(5)得到XML文档的根节点
                Element root=doc.getDocumentElement();
                //在DOM中只有根节点是一个org.w3c.dom.Element对象。
                //(6)得到节点的子节点
                NodeList books=root.getChildNodes();
               
                if(books!=null) {
                    for(int i=0;i<books.getLength();i++) {
                        Node book=books.item(i);
                       // if(book.getNodeType()==Node.ELEMENT_NODE) {
                            //(7)取得节点的属性值
                        //    String email=book.getAttributes().getNamedItem("email").getNodeValue();
                         //   System.out.println(email);
                            //注意,节点的属性也是它的子节点。它的节点类型也是Node.ELEMENT_NODE
                            //(8)轮循子节点
                            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("xml里面的name标签值:"+name1);
                                    }
                                    if(node.getNodeName().equals("price")) {
                                        String price=node.getFirstChild().getNodeValue();
                                        System.out.println("xml里面的price标签值:"+price);
                                    }
                               // }
                            }
                           
                            //
                        }
                    }//(6)这是用一个org.w3c.dom.NodeList接口来存放它所有子节点的,还有一种轮循子节点的方法,后面有介绍
                }
            } catch (ParserConfigurationException e)  {
                e.printStackTrace();
            } catch (FileNotFoundException e)  {
                e.printStackTrace();
            } catch (SAXException e)  {
                e.printStackTrace();
            } catch (IOException e)  {
                e.printStackTrace();
            }
        }

         public static void main(String[] args) {
           
             new ReadXml();
        }
}


<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>测试</name>
        <price>111</price>
    </book>
<book>
        <name>我的博客</name>
        <price>222</price>
    </book>
</books>



package org.show;

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ShowXml {
    public static void main (String argv []){
    try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("book.xml"));
            // normalize text redivsentation          
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
          
            NodeList listOfPersons = doc.getElementsByTagName("person");
            int totalPersons = listOfPersons.getLength();
            System.out.println("Total no of people : " + totalPersons);

            for(int s=0; s<listOfPersons.getLength() ; s++){
                Node firstPersonNode = listOfPersons.item(s);
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                    Element firstPersonElement = (Element)firstPersonNode;
                    //-------                  
                    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                    Element firstNameElement = (Element)firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out.println("First Name : " +
                           ((Node)textFNList.item(0)).getNodeValue().trim());

                    //-------                  
                    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                    Element lastNameElement = (Element)lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out.println("Last Name : " +
                           ((Node)textLNList.item(0)).getNodeValue().trim());

                    //----                  
                    NodeList ageList = firstPersonElement.getElementsByTagName("age");
                    Element ageElement = (Element)ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());

                    //------

                }//end of if clause

            }//end of for loop with s var

        }
        catch (SAXParseException err) {
               System.out.println ("** Parsing error" + ", line "
                                          + err.getLineNumber () + ", uri " + err.getSystemId ());
               System.out.println(" " + err.getMessage ());

        }
        catch (SAXException e) {
                Exception x = e.getException ();
                ((x == null) ? e : x).printStackTrace ();

        }
        catch (Throwable t) {
                t.printStackTrace ();
        }
        //System.exit (0);
    }//end of main

}


<?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
  <first>Kiran</first>
  <last>Pai</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>

你可能感兴趣的:(java,xml,J#,出版)