zoukankan      html  css  js  c++  java
  • java中调用xml的方法:DocumentBuilderFactory

    首先得到:得到 DOM 解析器的工厂实例      DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();

    然后DOM 工厂获得 DOM 解析器

     DocumentBuilder dombuilder=domfac.newDocumentBuilder();

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

    InputStream is= new  FileInputStream("test1.xml");        

    4 )解析 XML 文档的输入流,得到一个 Document

     Document doc=dombuilder.parse(is);

    5 )得到 XML 文档的根节点

    Element root=doc.getDocumentElement();

    6 )得到节点的子节点

      NodeList books=root.getChildNodes();

    1. package com.st.demo;   
    2.   
    3. import java.io.File;   
    4. import java.io.FileInputStream;   
    5. import java.io.InputStream;   
    6.   
    7. import javax.xml.parsers.DocumentBuilder;   
    8. import javax.xml.parsers.DocumentBuilderFactory;   
    9.   
    10. import org.w3c.dom.Document;   
    11. import org.w3c.dom.Element;   
    12. import org.w3c.dom.Node;   
    13. import org.w3c.dom.NodeList;   
    14.   
    15. public class XmlReader {   
    16.     public static void main(String[] args) {   
    17.         XmlReader reader = new XmlReader();   
    18.     }   
    19.     public XmlReader(){   
    20.         DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();   
    21.         try {   
    22.             DocumentBuilder domBuilder = domfac.newDocumentBuilder();   
    23.             InputStream is = new FileInputStream(new File("D:/test1.xml"));   
    24.             Document doc = domBuilder.parse(is);   
    25.             Element root = doc.getDocumentElement();   
    26.             NodeList books = root.getChildNodes();   
    27.             if(books!=null){   
    28.                 for (int i = 0; i < books.getLength(); i++) {   
    29.                     Node book = books.item(i);   
    30.                      if(book.getNodeType()==Node.ELEMENT_NODE) {   
    31.                             //(7)取得节点的属性值   
    32.                             String email=book.getAttributes().getNamedItem("email").getNodeValue();   
    33.                             System.out.println(email);   
    34.                             //注意,节点的属性也是它的子节点。它的节点类型也是Node.ELEMENT_NODE   
    35.                             //(8)轮循子节点   
    36.                             for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling()) {   
    37.                                 if(node.getNodeType()==Node.ELEMENT_NODE) {   
    38.                                     if(node.getNodeName().equals("name")) {   
    39.                                         String name=node.getNodeValue();   
    40.                                         String name1=node.getFirstChild().getNodeValue();   
    41.                                         System.out.println(name);   
    42.                                         System.out.println(name1);   
    43.                                     }   
    44.                                     if(node.getNodeName().equals("price")) {   
    45.                                         String price=node.getFirstChild().getNodeValue();   
    46.                                         System.out.println(price);   
    47.                                     }   
    48.                                 }   
    49.                             }   
    50.                      }   
    51.                 }   
    52.             }   
    53.         } catch (Exception e) {   
    54.             // TODO Auto-generated catch block   
    55.             e.printStackTrace();   
    56.         }   
    57.            
    58.     }   
    59. }  
    60.  
    Xml代码 复制代码
    1. <?xml version="1.0" encoding="GB2312" standalone="no"?>  
    2. <books>  
    3.     <book email="zhoujunhui">  
    4.         <name>rjzjh</name>  
    5.         <price>jjjjjj</price>  
    6.     </book>  
    7. </books>  

    java解析XML的三种方法

     

    1.SAX事件解析

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    package com.wzh.sax;
     
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
     
    //
    public class Saxhandler extends DefaultHandler {
     
        @Override
        public void startDocument() throws SAXException {
            System.out.println("开始解析XML文档...");
        }
     
        @Override
        public void endDocument() throws SAXException {
            System.out.println("结束解析XML文档...");
        }
     
        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            // TODO Auto-generated method stub
            super.startElement(uri, localName, qName, attributes);
            System.out.println("开始解析节点["+qName+"]...");
            System.out.println("共有["+attributes.getLength()+"]个属性");
        }
     
        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            // TODO Auto-generated method stub
            super.characters(ch, start, length);
            String content =new String(ch,start,length);
            System.out.println(content);
        }
     
        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            // TODO Auto-generated method stub
            super.endElement(uri, localName, qName);
            System.out.println("结束解析XML节点...");
        }
    }

      

    2.Dom加载解析

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    package com.wzh.dom;
     
    import java.util.Iterator;
     
    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 DomHandler {
     
        /*
         * 解析XML
         */
        public void read(String fileName) throws Exception {
            // 定义工厂API 使应用程序能够从XML文档获取生成DOM对象树的解析器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 获取此类的实例之后,将可以从各种输入源解析XML
            DocumentBuilder builder = factory.newDocumentBuilder();
            // builder.parse(this.getClass().getResourceAsStream("/" + fileName));
            // Document接口表示整个HTML或XML文档,从概念上讲,它是文档树的根,并提供对文档数据的基本访问
            Document document = builder.parse(this.getClass().getResourceAsStream(
                    "/" + fileName));
            // 获取根节点
            Element root = document.getDocumentElement();
            System.out.println(root.getNodeName());
     
            //读取database节点NodeList接口提供对节点的有序集合的抽象
            NodeList nodeList = root.getElementsByTagName("database");
            for (int i = 0; i < nodeList.getLength(); i++) {
                // 获取一个节点
                Node node = nodeList.item(i);
                // 获取该节点所有属性
                NamedNodeMap attributes = node.getAttributes();
                for (int j = 0; j < attributes.getLength(); j++) {
                    Node attribute = attributes.item(j);
                    System.out.println(attribute.getNodeName() + ":"
                            + attribute.getNodeValue());
                }
                //获取所有子节点数据
                NodeList childNodes=node.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node childNode=childNodes.item(j);
                    System.out.println(childNode.getNodeName()+":"+childNode.getNodeValue());
                }
            }
        }
     
        public static void main(String[] args) throws Exception {
            new DomHandler().read("data-source.xml");
     
        }
    }

      

    3.dom4j解析

    package com.wzh.dom4j;

    import java.io.FileOutputStream;
    import java.sql.DatabaseMetaData;
    import java.util.Iterator;
    import java.util.List;

    import org.dom4j.*;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.XMLWriter;

    public class Dom4jHandler {

    public void add() throws Exception {
    // 1.创建一个Document
    Document document = DocumentHelper.createDocument();
    // 2.给Document添加数据
    Element root = document.addElement("DataSource");
    // 添加注释
    root.addComment("这是注释信息");
    // 在root根节点下面添加一个子节点
    Element database = root.addElement("database");
    database.addAttribute("name", "mysql");
    database.addAttribute("version", "5.0");
    // 添加子节点
    database.addElement("driver").setText("com.mysql.jdbc.Driver");
    database.addElement("url")
    .setText("jdbc:mysql://localhost:3306/myjdbc");
    database.addElement("user").setText("root");
    database.addElement("password").setText("root");
    // 3.将Document写出文件
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("utf-8");
    // FileOutputStream默认生成的路径在根路径
    XMLWriter xw = new XMLWriter(new FileOutputStream("db.xml"), format);
    xw.write(document);
    xw.close();
    }

    public void update(String fileName) throws Exception {
    // sax解析器
    SAXReader saxReader = new SAXReader();
    // 读到对象
    Document document = saxReader.read(this.getClass().getResourceAsStream(
    "/" + fileName));
    Element root = document.getRootElement();
    List<Element> databases_node = root.elements("database");
    for (Element database_node : databases_node) {
    if (database_node.attributeValue("name").equalsIgnoreCase("mysql")) {
    System.out.println("old:"
    + database_node.attributeValue("name"));
    database_node.attribute("name").setText("Oracle");
    System.out.println("update:"
    + database_node.attributeValue("name"));

    database_node.element("driver").setText("oracel");
    database_node.element("url").setText("jdbc");

    // 删除password节点
    database_node.remove(database_node.element("password"));

    // 删除属性
    database_node.remove(database_node.attribute("version"));
    }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("utf-8");
    // FileOutputStream默认生成的路径在根路径
    XMLWriter xw = new XMLWriter(new FileOutputStream("db2.xml"), format);
    xw.write(document);
    xw.close();
    }

    public void read(String fileName) throws Exception {
    // sax解析器
    SAXReader saxReader = new SAXReader();
    // 读到对象
    Document document = saxReader.read(this.getClass().getResourceAsStream(
    "/" + fileName));
    Element root = document.getRootElement();
    System.out.println("根节点:" + root.getName());

    // List<Element> childElements=root.elements();
    List<Element> childElements = root.elements("database");
    for (Element child : childElements) {
    // 获取属性 不知道属性名称时的遍历方法
    List<Attribute> attributes = child.attributes();
    // for (Attribute attribute : attributes) {
    // System.out.println(attribute.getName()+":"+attribute.getValue());
    // }
    String name = child.attributeValue("name");
    // String version = child.attributeValue("version");
    String version = child.attribute("version").getValue();
    System.out.println(name + ":" + version);

    // //获取子节点
    // List<Element> childs=child.elements();
    // for (Element element : childs) {
    // System.out.println(element.getName()+":"+element.getText());
    // }
    System.out.println(child.elementText("driver"));
    System.out.println(child.element("url").getText());
    System.out.println(child.elementTextTrim("user"));
    System.out.println(child.element("password").getTextTrim());

    }
    }

    public static void main(String[] args) throws Exception {
    // new Dom4jHandler().read("data-source.xml");
    // new Dom4jHandler().add();
    new Dom4jHandler().update("data-source.xml");
    }
    }

      

  • 相关阅读:
    在Ubuntu下依然爱SOGO
    CompositePattern(23种设计模式之一)
    Arduino String.h库函数详解
    cp命令详解
    PHP AJAX 返回JSON 数据
    PHP AJAX返回 "TEXT"
    PHP JSON数据 AJAX
    PHP JQurey
    PHP 封装POD 类
    PHP 分页+查询
  • 原文地址:https://www.cnblogs.com/jiangyi666/p/5677785.html
Copyright © 2011-2022 走看看