溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

xml的四種解析方法及源代碼怎么寫

發(fā)布時間:2021-10-13 14:47:41 來源:億速云 閱讀:109 作者:柒染 欄目:編程語言

本篇文章為大家展示了xml的四種解析方法及源代碼怎么寫,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

這個也是自己轉(zhuǎn)載的,現(xiàn)在對DOM還比較熟悉,自己不要只是復(fù)制代碼,可以試著去熟悉其中的一兩種,以后會有用處的。

xml的四種解析方法及源代碼(SAX、DOM、JDOM、DOM4J)

第一種:SAX解析 
SAX處理機制:SAX是一種基于事件驅(qū)動的API。利用SAX解析XML文檔,牽涉到兩個部分:解析器和事件處理器。解析器負(fù)責(zé)讀取XML文檔,并向事件處理器發(fā)生事件,如元素開始和元素結(jié)束事件;而事件處理器則負(fù)責(zé)對事件做出響應(yīng),對傳遞的XML數(shù)據(jù)進行處理。

測試用的xml文件:db.xml

Xml代碼 

<?xml version="1.0" encoding="UTF-8"?>  

<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->  

<dbconfig>  

 <db type="oracle">  

  <driver>oracle.jdbc.driver.OracleDriver</driver>  

  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>  

  <user>scott</user>  

  <password>tiger</password>  

 </db>  

</dbconfig>  

<?xml version="1.0" encoding="UTF-8"?>

<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->

<dbconfig>

 <db type="oracle">

  <driver>oracle.jdbc.driver.OracleDriver</driver>

  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>

  <user>scott</user>

  <password>tiger</password>

 </db>

</dbconfig>

DTD文件db.dtd

Xml代碼 

<!ELEMENT dbconfig (db+)>  

<!ELEMENT db (driver,url,user,password)>  

<!ELEMENT driver (#PCDATA)>  

<!ELEMENT url (#PCDATA)>  

<!ELEMENT user (#PCDATA)>  

<!ELEMENT password (#PCDATA)>  

<!ATTLIST db type CDATA #REQUIRED>  

<!ELEMENT dbconfig (db+)>

<!ELEMENT db (driver,url,user,password)>

<!ELEMENT driver (#PCDATA)>

<!ELEMENT url (#PCDATA)>

<!ELEMENT user (#PCDATA)>

<!ELEMENT password (#PCDATA)>

<!ATTLIST db type CDATA #REQUIRED>

SAX解析實例一
org.xml.sax.DefalutHandler類:  可以擴展該類,給出自己的解析實現(xiàn)
SAXPrinter.java

Java代碼 

import java.io.File;   

  

import javax.xml.parsers.SAXParser;   

import javax.xml.parsers.SAXParserFactory;   

  

import org.xml.sax.Attributes;   

import org.xml.sax.SAXException;   

import org.xml.sax.helpers.DefaultHandler;   

  

public class SAXPrinter extends DefaultHandler   

{   

  

  /** *//**  

   * 文檔開始事件  

   */  

    public void startDocument() throws SAXException   

    {   

        System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");   

    }   

       

  /** *//**  

   * 接收處理指令事件  

   */  

    public void processingInstruction(String target, String data) throws SAXException   

    {   

        System.out.println("<?"+target+" "+data+"?>");   

    }   

       

  /** *//**  

   * 元素開始事件  

   * 參數(shù)說明:  

   *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執(zhí)行名稱空間處理,則為空字符串。  

   *   localName - 本地名稱(不帶前綴),如果沒有正在執(zhí)行名稱空間處理,則為空字符串。  

   *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則為空字符串。  

   *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。  

   */  

    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException   

    {   

        System.out.print("<"+qName);//輸出元素名稱   

        int len=attrs.getLength();//元素屬性列表長度   

           

    //利用循環(huán)輸出屬性列表   

        for(int i=0;i<len;i++)   

        {   

            System.out.print(" ");   

            System.out.print(attrs.getQName(i));   

            System.out.print("=\"");   

            System.out.print(attrs.getValue(i));   

            System.out.print("\"");   

        }   

        System.out.print(">");   

    }   

       

  /** *//**  

   * 元素中字符數(shù)據(jù)事件:接收元素中字符數(shù)據(jù)  

   * 注意:1.應(yīng)用程序不要試圖讀取ch數(shù)組指定范圍外的數(shù)據(jù),(即start至length之外)  

   *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內(nèi)容中的空白,而不是characters()方法,如:進行有效性驗證的解析器  

   */  

    public void characters(char[] ch, int start, int length) throws SAXException   

    {   

        System.out.print(new String(ch,start,length));   

    }   

  

  /** *//**  

   * 結(jié)束元素事件  

   */  

    public void endElement(String uri, String localName, String qName) throws SAXException   

    {   

        System.out.print("</"+qName+">");   

    }   

  

    public static void main(String[] args)   

    {   

        SAXParserFactory spf=SAXParserFactory.newInstance();   

           

        try  

        {   

            SAXParser sp=spf.newSAXParser();   

            sp.parse(new File("db.xml"),new SAXPrinter());   

        }   

        catch (Exception e)   

        {   

            e.printStackTrace();   

        }   

    }   

}  

import java.io.File;


import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;


public class SAXPrinter extends DefaultHandler

{


  /** *//**

   * 文檔開始事件

   */

    public void startDocument() throws SAXException

    {

        System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

    }

    

  /** *//**

   * 接收處理指令事件

   */

    public void processingInstruction(String target, String data) throws SAXException

    {

        System.out.println("<?"+target+" "+data+"?>");

    }

    

  /** *//**

   * 元素開始事件

   * 參數(shù)說明:

   *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執(zhí)行名稱空間處理,則為空字符串。

   *   localName - 本地名稱(不帶前綴),如果沒有正在執(zhí)行名稱空間處理,則為空字符串。

   *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則為空字符串。

   *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。

   */

    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException

    {

        System.out.print("<"+qName);//輸出元素名稱

        int len=attrs.getLength();//元素屬性列表長度

        

    //利用循環(huán)輸出屬性列表

        for(int i=0;i<len;i++)

        {

            System.out.print(" ");

            System.out.print(attrs.getQName(i));

            System.out.print("=\"");

            System.out.print(attrs.getValue(i));

            System.out.print("\"");

        }

        System.out.print(">");

    }

    

  /** *//**

   * 元素中字符數(shù)據(jù)事件:接收元素中字符數(shù)據(jù)

   * 注意:1.應(yīng)用程序不要試圖讀取ch數(shù)組指定范圍外的數(shù)據(jù),(即start至length之外)

   *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內(nèi)容中的空白,而不是characters()方法,如:進行有效性驗證的解析器

   */

    public void characters(char[] ch, int start, int length) throws SAXException

    {

        System.out.print(new String(ch,start,length));

    }


  /** *//**

   * 結(jié)束元素事件

   */

    public void endElement(String uri, String localName, String qName) throws SAXException

    {

        System.out.print("</"+qName+">");

    }


    public static void main(String[] args)

    {

        SAXParserFactory spf=SAXParserFactory.newInstance();

        

        try

        {

            SAXParser sp=spf.newSAXParser();

            sp.parse(new File("db.xml"),new SAXPrinter());

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

    }

}

SAX解析實例二
org.xml.sax.ContentHandler接口: 通過實現(xiàn)該接口給出自己的解析實現(xiàn)。
org.xml.sax.ErrorHandler接口:如果SAX應(yīng)用程序需要實現(xiàn)定制的錯誤處理,那么它必須實現(xiàn)這個接口,并調(diào)用XMLReader對象的setErrorHandler()方法向解析器注冊異常處理實例,這樣,解析器將通過這個接口報告所有的錯誤和警告。
ContentHandlerImpl.java

Java代碼 

import org.xml.sax.Attributes;   

import org.xml.sax.ContentHandler;   

import org.xml.sax.Locator;   

import org.xml.sax.SAXException;   

  

public class ContentHandlerImpl implements ContentHandler   

{   

  /** *//**  

   * 文檔開始事件  

   */  

  public void startDocument() throws SAXException   

  {   

    System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");   

  }   

     

  /** *//**  

   * 接收處理指令事件  

   */  

  public void processingInstruction(String target, String data) throws SAXException   

  {   

    System.out.println("<?"+target+" "+data+"?>");   

  }   

     

  /** *//**  

   * 元素開始事件  

   * 參數(shù)說明:  

   *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執(zhí)行名稱空間處理,則為空字符串。  

   *   localName - 本地名稱(不帶前綴),如果沒有正在執(zhí)行名稱空間處理,則為空字符串。  

   *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則為空字符串。  

   *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。  

   */  

  public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException   

  {   

    System.out.print("<"+qName);//輸出元素名稱   

    int len=attrs.getLength();//元素屬性列表長度   

       

    //利用循環(huán)輸出屬性列表   

    for(int i=0;i<len;i++)   

    {   

      System.out.print(" ");   

      System.out.print(attrs.getQName(i));   

      System.out.print("=\"");   

      System.out.print(attrs.getValue(i));   

      System.out.print("\"");   

    }   

    System.out.print(">");   

  }   

     

  /** *//**  

   * 元素中字符數(shù)據(jù)事件:接收元素中字符數(shù)據(jù)  

   * 注意:1.應(yīng)用程序不要試圖讀取ch數(shù)組指定范圍外的數(shù)據(jù),(即start至length之外)  

   *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內(nèi)容中的空白,而不是characters()方法,如:進行有效性驗證的解析器  

   */  

  public void characters(char[] ch, int start, int length) throws SAXException   

  {   

    System.out.print(new String(ch,start,length));   

  }   

  

  /** *//**  

   * 結(jié)束元素事件  

   */  

  public void endElement(String uri, String localName, String qName) throws SAXException   

  {   

    System.out.print("</"+qName+">");   

  }   

  

  public void endDocument() throws SAXException   

  {   

       

  }   

  

  public void endPrefixMapping(String prefix) throws SAXException   

  {   

       

  }   

  

  public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException   

  {   

       

  }   

  

  public void setDocumentLocator(Locator locator)   

  {   

       

  }   

  

  public void skippedEntity(String name) throws SAXException   

  {   

       

  }   

  

  public void startPrefixMapping(String prefix, String uri) throws SAXException   

  {   

       

  }   

  

}   

import org.xml.sax.Attributes;

import org.xml.sax.ContentHandler;

import org.xml.sax.Locator;

import org.xml.sax.SAXException;


public class ContentHandlerImpl implements ContentHandler

{

  /** *//**

   * 文檔開始事件

   */

  public void startDocument() throws SAXException

  {

    System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

  }

  

  /** *//**

   * 接收處理指令事件

   */

  public void processingInstruction(String target, String data) throws SAXException

  {

    System.out.println("<?"+target+" "+data+"?>");

  }

  

  /** *//**

   * 元素開始事件

   * 參數(shù)說明:

   *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執(zhí)行名稱空間處理,則為空字符串。

   *   localName - 本地名稱(不帶前綴),如果沒有正在執(zhí)行名稱空間處理,則為空字符串。

   *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則為空字符串。

   *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。

   */

  public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException

  {

    System.out.print("<"+qName);//輸出元素名稱

    int len=attrs.getLength();//元素屬性列表長度

    

    //利用循環(huán)輸出屬性列表

    for(int i=0;i<len;i++)

    {

      System.out.print(" ");

      System.out.print(attrs.getQName(i));

      System.out.print("=\"");

      System.out.print(attrs.getValue(i));

      System.out.print("\"");

    }

    System.out.print(">");

  }

  

  /** *//**

   * 元素中字符數(shù)據(jù)事件:接收元素中字符數(shù)據(jù)

   * 注意:1.應(yīng)用程序不要試圖讀取ch數(shù)組指定范圍外的數(shù)據(jù),(即start至length之外)

   *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內(nèi)容中的空白,而不是characters()方法,如:進行有效性驗證的解析器

   */

  public void characters(char[] ch, int start, int length) throws SAXException

  {

    System.out.print(new String(ch,start,length));

  }


  /** *//**

   * 結(jié)束元素事件

   */

  public void endElement(String uri, String localName, String qName) throws SAXException

  {

    System.out.print("</"+qName+">");

  }


  public void endDocument() throws SAXException

  {

    

  }


  public void endPrefixMapping(String prefix) throws SAXException

  {

    

  }


  public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException

  {

    

  }


  public void setDocumentLocator(Locator locator)

  {

    

  }


  public void skippedEntity(String name) throws SAXException

  {

    

  }


  public void startPrefixMapping(String prefix, String uri) throws SAXException

  {

    

  }


}

ErrorHandlerImpl.java  

Java代碼 

public class ErrorHandlerImpl implements ErrorHandler   

{   

  

  public void warning(SAXParseException e) throws SAXException   

  {   

    System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());   

  }   

  

  public void error(SAXParseException e) throws SAXException   

  {   

    System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());   

  }   

  

  public void fatalError(SAXParseException e) throws SAXException   

  {   

    System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());   

  }   

  

  private String getLocationString(SAXParseException e)   

  {   

    StringBuffer sb=new StringBuffer();   

    String publicId=e.getPublicId();   

    if(publicId!=null)   

    {   

      sb.append(publicId);   

      sb.append(" ");   

    }   

       

    String systemId=e.getSystemId();   

    if(systemId!=null)   

    {   

      sb.append(systemId);   

      sb.append(" ");   

    }   

       

    sb.append(e.getLineNumber());   

    sb.append(":");   

    sb.append(e.getColumnNumber());   

    return sb.toString();   

  }   

1. }  

public class ErrorHandlerImpl implements ErrorHandler

{


  public void warning(SAXParseException e) throws SAXException

  {

    System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());

  }


  public void error(SAXParseException e) throws SAXException

  {

    System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());

  }


  public void fatalError(SAXParseException e) throws SAXException

  {

    System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());

  }


  private String getLocationString(SAXParseException e)

  {

    StringBuffer sb=new StringBuffer();

    String publicId=e.getPublicId();

    if(publicId!=null)

    {

      sb.append(publicId);

      sb.append(" ");

    }

    

    String systemId=e.getSystemId();

    if(systemId!=null)

    {

      sb.append(systemId);

      sb.append(" ");

    }

    

    sb.append(e.getLineNumber());

    sb.append(":");

    sb.append(e.getColumnNumber());

    return sb.toString();

  }

}

SaxParserTest.java  

Java代碼 

import java.io.FileInputStream;   

  

import org.xml.sax.InputSource;   

import org.xml.sax.XMLReader;   

import org.xml.sax.helpers.XMLReaderFactory;   

  

public class SaxParserTest   

{   

  public static void main(String[] args)   

  {   

    try  

    {   

      XMLReader xmlReader=XMLReaderFactory.createXMLReader();   

      //關(guān)閉或打開驗證   

      xmlReader.setFeature("http://xml.org/sax/features/validation",true);   

      //注冊事件處理器   

      xmlReader.setContentHandler(new ContentHandlerImpl());   

      //注冊異常處理器   

      xmlReader.setErrorHandler(new ErrorHandlerImpl());   

         

      xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));   

    } catch (Exception e)   

    {   

      System.out.println(e.getMessage());   

    }   

  }   

}  

import java.io.FileInputStream;


import org.xml.sax.InputSource;

import org.xml.sax.XMLReader;

import org.xml.sax.helpers.XMLReaderFactory;


public class SaxParserTest

{

  public static void main(String[] args)

  {

    try

    {

      XMLReader xmlReader=XMLReaderFactory.createXMLReader();

      //關(guān)閉或打開驗證

      xmlReader.setFeature("http://xml.org/sax/features/validation",true);

      //注冊事件處理器

      xmlReader.setContentHandler(new ContentHandlerImpl());

      //注冊異常處理器

      xmlReader.setErrorHandler(new ErrorHandlerImpl());

      

      xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));

    } catch (Exception e)

    {

      System.out.println(e.getMessage());

    }

  }

}

第二種:DOM解析
DOM中的核心概念就是節(jié)點。DOM在分析XML文檔時,將將組成XML文檔的各個部分(元素、屬性、文本、注釋、處理指令等)映射為一個對象(節(jié)點)。在內(nèi)存中,這些節(jié)點形成一課文檔樹。整棵樹是一個節(jié)點,樹中的每一個節(jié)點也是一棵樹(子樹),可以說,DOM就是對這棵樹的一個對象描述,我們通過訪問樹中的節(jié)點來存取XML文檔的內(nèi)容。
PS:屬性節(jié)點是附屬于元素的,不能被看做是元素的子節(jié)點,更不能作為一個單獨的節(jié)點

DOMPrinter.java

Java代碼 

import org.w3c.dom.Document;   

import org.w3c.dom.NamedNodeMap;   

import org.w3c.dom.Node;   

  

import com.sun.org.apache.xerces.internal.parsers.DOMParser;   

  

public class DOMPrinter   

{   

  public static void main(String[] args)   

  {   

    try  

    {   

      /** *//** 獲取Document對象 */  

      DOMParser parser = new DOMParser();   

      parser.parse("db.xml");   

      Document document = parser.getDocument();   

      printNode(document);   

    } catch (Exception e)   

    {   

      e.printStackTrace();   

    }   

  }   

     

  public static void printNode(Node node)   

  {   

    short nodeType=node.getNodeType();   

    switch(nodeType)   

    {   

    case Node.PROCESSING_INSTRUCTION_NODE://預(yù)處理指令類型   

      printNodeInfo(node);   

      break;   

    case Node.ELEMENT_NODE://元素節(jié)點類型   

      printNodeInfo(node);   

      printAttribute(node);   

      break;   

    case Node.TEXT_NODE://文本節(jié)點類型   

      printNodeInfo(node);   

      break;   

    default:   

      break;   

    }   

       

    Node child=node.getFirstChild();   

    while(child!=null)   

    {   

      printNode(child);   

      child=child.getNextSibling();   

    }   

  }   

     

  /** *//**  

   * 根據(jù)節(jié)點類型打印節(jié)點  

   * @param node  

   */  

  public static void printNodeInfo(Node node)   

  {   

    if (node.getNodeType() == Node.ELEMENT_NODE)   

    {   

      System.out.println("NodeName: " + node.getNodeName());   

    }   

    else if (node.getNodeType() == Node.TEXT_NODE)   

    {   

      String value = node.getNodeValue().trim();   

      if (!value.equals(""))   

        System.out.println("NodeValue: " + value);   

      else  

        System.out.println();   

    }else  

    {   

      System.out.println(node.getNodeName()+" : "+node.getNodeValue());   

    }   

  }   

     

  /** *//**  

   * 打印節(jié)點屬性  

   * @param aNode 節(jié)點  

   */  

  public static void printAttribute(Node aNode)   

  {   

    NamedNodeMap attrs = aNode.getAttributes();   

    if(attrs!=null)   

    {   

      for (int i = 0; i < attrs.getLength(); i++)   

      {   

        Node attNode = attrs.item(i);   

        System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");   

      }   

    }   

  }  

import org.w3c.dom.Document;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;


import com.sun.org.apache.xerces.internal.parsers.DOMParser;


public class DOMPrinter

{

  public static void main(String[] args)

  {

    try

    {

      /** *//** 獲取Document對象 */

      DOMParser parser = new DOMParser();

      parser.parse("db.xml");

      Document document = parser.getDocument();

      printNode(document);

    } catch (Exception e)

    {

      e.printStackTrace();

    }

  }

  

  public static void printNode(Node node)

  {

    short nodeType=node.getNodeType();

    switch(nodeType)

    {

    case Node.PROCESSING_INSTRUCTION_NODE://預(yù)處理指令類型

      printNodeInfo(node);

      break;

    case Node.ELEMENT_NODE://元素節(jié)點類型

      printNodeInfo(node);

      printAttribute(node);

      break;

    case Node.TEXT_NODE://文本節(jié)點類型

      printNodeInfo(node);

      break;

    default:

      break;

    }

    

    Node child=node.getFirstChild();

    while(child!=null)

    {

      printNode(child);

      child=child.getNextSibling();

    }

  }

  

  /** *//**

   * 根據(jù)節(jié)點類型打印節(jié)點

   * @param node

   */

  public static void printNodeInfo(Node node)

  {

    if (node.getNodeType() == Node.ELEMENT_NODE)

    {

      System.out.println("NodeName: " + node.getNodeName());

    }

    else if (node.getNodeType() == Node.TEXT_NODE)

    {

      String value = node.getNodeValue().trim();

      if (!value.equals(""))

        System.out.println("NodeValue: " + value);

      else

        System.out.println();

    }else

    {

      System.out.println(node.getNodeName()+" : "+node.getNodeValue());

    }

  }

  

  /** *//**

   * 打印節(jié)點屬性

   * @param aNode 節(jié)點

   */

  public static void printAttribute(Node aNode)

  {

    NamedNodeMap attrs = aNode.getAttributes();

    if(attrs!=null)

    {

      for (int i = 0; i < attrs.getLength(); i++)

      {

        Node attNode = attrs.item(i);

        System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");

      }

    }

  }

DOM生成XML文檔:DOMCreateExample.java  

Java代碼 

import java.io.FileNotFoundException;   

import java.io.FileOutputStream;   

import java.io.IOException;   

  

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 com.sun.org.apache.xml.internal.serialize.XMLSerializer;   

  

public class DOMCreateExample   

{   

  public static void main(String[] args) throws ParserConfigurationException   

  {   

    //DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation();   

    DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance();   

    DocumentBuilder builder = builderFact.newDocumentBuilder();   

      

    Document doc = builder.newDocument();   

    //Document doc = domImp.createDocument(null, null, null);   

      

    Element root = doc.createElement("games");   

    Element child1 = doc.createElement("game");   

    child1.appendChild(doc.createTextNode("Final Fantasy VII"));   

    child1.setAttribute("genre", "rpg");   

    root.appendChild(child1);   

    doc.appendChild(root);   

        

     XMLSerializer serial;   

    try  

    {   

      serial = new XMLSerializer(new FileOutputStream("domcreate.xml"), null);   

      serial.serialize(doc);   

    } catch (FileNotFoundException e1)   

    {   

      e1.printStackTrace();   

    } catch (IOException e)   

    {   

      e.printStackTrace();   

    }   

  }   

}  

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;


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 com.sun.org.apache.xml.internal.serialize.XMLSerializer;


public class DOMCreateExample

{

  public static void main(String[] args) throws ParserConfigurationException

  {

    //DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation();

    DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance();

    DocumentBuilder builder = builderFact.newDocumentBuilder();

   

    Document doc = builder.newDocument();

    //Document doc = domImp.createDocument(null, null, null);

   

    Element root = doc.createElement("games");

    Element child1 = doc.createElement("game");

    child1.appendChild(doc.createTextNode("Final Fantasy VII"));

    child1.setAttribute("genre", "rpg");

    root.appendChild(child1);

    doc.appendChild(root);

     

     XMLSerializer serial;

    try

    {

      serial = new XMLSerializer(new FileOutputStream("domcreate.xml"), null);

      serial.serialize(doc);

    } catch (FileNotFoundException e1)

    {

      e1.printStackTrace();

    } catch (IOException e)

    {

      e.printStackTrace();

    }

  }

}

第三種JDOM解析 
JDOM利用了java語言的優(yōu)秀特性,極大地簡化了對XML文檔的處理,相比DOM簡單易用。JDOM也使用對象樹來表示XML文檔,JDOM使用SAXj解析器來分析XML文檔,構(gòu)建JDOM樹。然而JOMD本身并沒有提供解析器,它使用其他開發(fā)商提供的標(biāo)準(zhǔn)SAX解析器,JDOM默認(rèn)通過JAXP來選擇解析器,可以通過手動知道解析器的類名來設(shè)置。
首先要在工程中添加jdom的jar包,這里使用jdom1.0.jar。(見附件)
JDOMConvert.java 

Java代碼 

import java.io.File;   

  

import org.jdom.Document;   

import org.jdom.Element;   

import org.jdom.input.SAXBuilder;   

import org.jdom.output.Format;   

import org.jdom.output.XMLOutputter;   

  

public class JDOMConvert   

{   

    public static void main(String[] args)   

    {   

        SAXBuilder saxBuilder=new SAXBuilder();   

        try  

        {   

            Document doc=saxBuilder.build(new File("domdb.xml"));   

         

      //首先創(chuàng)建好節(jié)點   

      Element eltDb=new Element("db");   

      Element eltDriver=new Element("driver");   

      Element eltUrl=new Element("url");   

      Element eltUser=new Element("user");   

      Element eltPassword=new Element("password");   

         

      //設(shè)置節(jié)點的值   

      eltDriver.setText("com.mysql.jdbc.Driver");   

      eltUrl.setText("jdbc:mysql://localhost/mySql");   

      eltUser.setText("root");   

      eltPassword.setText("xlc");   

         

      //添加到根節(jié)點   

      eltDb.addContent(eltDriver);   

      eltDb.addContent(eltUrl);   

      eltDb.addContent(eltUser);   

      eltDb.addContent(eltPassword);   

      //根節(jié)點設(shè)置屬性   

      eltDb.setAttribute("type","mysql");   

         

      Element root=doc.getRootElement();   

      //root.removeChild("db");//刪除節(jié)點   

      root.addContent(eltDb);//增加節(jié)點   

         

      //修改db節(jié)點中內(nèi)容   

      root.getChild("db").getChild("user").setText("system");   

      root.getChild("db").getChild("password").setText("manager");   

         

            XMLOutputter xmlOut=new XMLOutputter();   

               

      //設(shè)置XML格式   

            Format fmt=Format.getPrettyFormat();   

            fmt.setIndent("    ");   

            fmt.setEncoding("utf-8");   

               

            xmlOut.setFormat(fmt);   

            xmlOut.output(doc,System.out);   

        }   

        catch (Exception e)   

        {   

            e.printStackTrace();   

        }   

    }   

}  

import java.io.File;


import org.jdom.Document;

import org.jdom.Element;

import org.jdom.input.SAXBuilder;

import org.jdom.output.Format;

import org.jdom.output.XMLOutputter;


public class JDOMConvert

{

    public static void main(String[] args)

    {

        SAXBuilder saxBuilder=new SAXBuilder();

        try

        {

            Document doc=saxBuilder.build(new File("domdb.xml"));

      

      //首先創(chuàng)建好節(jié)點

      Element eltDb=new Element("db");

      Element eltDriver=new Element("driver");

      Element eltUrl=new Element("url");

      Element eltUser=new Element("user");

      Element eltPassword=new Element("password");

      

      //設(shè)置節(jié)點的值

      eltDriver.setText("com.mysql.jdbc.Driver");

      eltUrl.setText("jdbc:mysql://localhost/mySql");

      eltUser.setText("root");

      eltPassword.setText("xlc");

      

      //添加到根節(jié)點

      eltDb.addContent(eltDriver);

      eltDb.addContent(eltUrl);

      eltDb.addContent(eltUser);

      eltDb.addContent(eltPassword);

      //根節(jié)點設(shè)置屬性

      eltDb.setAttribute("type","mysql");

      

      Element root=doc.getRootElement();

      //root.removeChild("db");//刪除節(jié)點

      root.addContent(eltDb);//增加節(jié)點

      

      //修改db節(jié)點中內(nèi)容

      root.getChild("db").getChild("user").setText("system");

      root.getChild("db").getChild("password").setText("manager");

      

            XMLOutputter xmlOut=new XMLOutputter();

            

      //設(shè)置XML格式

            Format fmt=Format.getPrettyFormat();

            fmt.setIndent("    ");

            fmt.setEncoding("utf-8");

            

            xmlOut.setFormat(fmt);

            xmlOut.output(doc,System.out);

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

    }

}

JDOM生成XML文檔:JDOMCreate.java  

Java代碼 

import java.io.IOException;   

  

import org.jdom.Document;   

import org.jdom.Element;   

import org.jdom.output.XMLOutputter;   

  

public class JDOMCreate   

{   

  public static void main(String[] args)   

  {   

    Document doc = new Document(new Element("games"));   

    Element newGame = new Element("game").setText("Final Fantasy VI");   

    doc.getRootElement().addContent(newGame);   

    newGame.setAttribute("genre", "rpg");   

    XMLOutputter domstream = new XMLOutputter();   

    try  

    {   

      domstream.output(doc, System.out);   

    } catch (IOException e)   

    {   

      e.printStackTrace();   

    }   

  }   

}  

import java.io.IOException;


import org.jdom.Document;

import org.jdom.Element;

import org.jdom.output.XMLOutputter;


public class JDOMCreate

{

  public static void main(String[] args)

  {

    Document doc = new Document(new Element("games"));

    Element newGame = new Element("game").setText("Final Fantasy VI");

    doc.getRootElement().addContent(newGame);

    newGame.setAttribute("genre", "rpg");

    XMLOutputter domstream = new XMLOutputter();

    try

    {

      domstream.output(doc, System.out);

    } catch (IOException e)

    {

      e.printStackTrace();

    }

  }

}

第四種:DOM4J解析
dom4j與JDOM一樣,也是一種用于解析XML文檔的開放源代碼的XML框架,dom4j也應(yīng)用于java平臺,dom4j API使用了java集合框架并完全支持DOM、SAX和JAXP。與JDOM不同的是,dom4j使用接口和抽象類,雖然dom4j的API相對復(fù)雜些,但它提供了比JDOM更好的靈活性。dom4j也使用SAX解析器來分析XML文檔,創(chuàng)建dom4j樹。此外dom4j也可以接收DOM格式的內(nèi)容,并提供了從dom4j樹到SAX事件流或W3C DOM樹的輸出機制。與JDOM不同,dom4j自帶了一個SAX解析器Aelfred2,如果沒有顯示的設(shè)置SAX解析器,也沒有通過系統(tǒng)屬性org.xml.sax.driver設(shè)置解析器,dom3j將會使用JAXP來加載JAXP配置的解析器,如果創(chuàng)建解析器失敗,那么最后才使用dom4j自帶的Aelfred2解析器。
同樣,首先要在工程中添加dom4j的jar包,這里使用dom4j-1.6.1.jar。(見附件)
Dom4j生成XML文檔db.xml:Dom4jCreate.java 

Java代碼 

import java.io.IOException;   

  

import org.dom4j.Document;   

import org.dom4j.DocumentHelper;   

import org.dom4j.Element;   

import org.dom4j.io.OutputFormat;   

import org.dom4j.io.XMLWriter;   

  

public class Dom4jCreate   

{   

  

  public static void main(String[] args)   

  {   

    Document doc = DocumentHelper.createDocument();   

  

    doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl' href='db.xsl'");   

    doc.addDocType("dbconfig", null,"db.dtd");   

       

    //Element root=DocumentHelper.createElement("dbconfig");   

    // doc.setRootElement(root);   

    Element root = doc.addElement("dbconfig");   

  

    Element eltDb= root.addElement("db");   

    Element eltDriver = eltDb.addElement("driver");   

    Element eltUrl = eltDb.addElement("url");   

    Element eltUser = eltDb.addElement("user");   

    Element eltPassword = eltDb.addElement("password");   

       

    eltDriver.setText("com.mysql.jdbc.Driver");   

    eltUrl.setText("jdbc:mysql://localhost/mySql");   

    eltUser.setText("root");   

    eltPassword.setText("xlc");   

    eltDb.addAttribute("type","mysql");   

           

    try  

    {   

      //設(shè)置輸出格式   

      OutputFormat outFmt = new OutputFormat("    ", true);   

      outFmt.setEncoding("UTF-8");   

         

      /**//*PrintWriter pw = new PrintWriter(System.out);  

      doc.write(pw);  

      pw.flush();  

      pw.close();*/  

  

      XMLWriter xmlWriter = new XMLWriter(System.out, outFmt);   

      // XMLWriter xmlWriter=new XMLWriter(new FileWriter("db.xml"),outFmt);   

      xmlWriter.write(doc);   

      xmlWriter.flush();   

      xmlWriter.close();   

    } catch (IOException e)   

    {   

      e.printStackTrace();   

    }   

  }   

}  

import java.io.IOException;


import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;


public class Dom4jCreate

{


  public static void main(String[] args)

  {

    Document doc = DocumentHelper.createDocument();


    doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl' href='db.xsl'");

    doc.addDocType("dbconfig", null,"db.dtd");

    

    //Element root=DocumentHelper.createElement("dbconfig");

    // doc.setRootElement(root);

    Element root = doc.addElement("dbconfig");


    Element eltDb= root.addElement("db");

    Element eltDriver = eltDb.addElement("driver");

    Element eltUrl = eltDb.addElement("url");

    Element eltUser = eltDb.addElement("user");

    Element eltPassword = eltDb.addElement("password");

    

    eltDriver.setText("com.mysql.jdbc.Driver");

    eltUrl.setText("jdbc:mysql://localhost/mySql");

    eltUser.setText("root");

    eltPassword.setText("xlc");

    eltDb.addAttribute("type","mysql");

        

    try

    {

      //設(shè)置輸出格式

      OutputFormat outFmt = new OutputFormat("    ", true);

      outFmt.setEncoding("UTF-8");

      

      /**//*PrintWriter pw = new PrintWriter(System.out);

      doc.write(pw);

      pw.flush();

      pw.close();*/


      XMLWriter xmlWriter = new XMLWriter(System.out, outFmt);

      // XMLWriter xmlWriter=new XMLWriter(new FileWriter("db.xml"),outFmt);

      xmlWriter.write(doc);

      xmlWriter.flush();

      xmlWriter.close();

    } catch (IOException e)

    {

      e.printStackTrace();

    }

  }

}

Dom4j修改XML文檔db.xml:Dom4jModify.java 

Java代碼 

import java.io.File;   

import java.io.FileWriter;   

import java.util.Iterator;   

import java.util.List;   

  

import org.dom4j.Document;   

import org.dom4j.Element;   

import org.dom4j.io.OutputFormat;   

import org.dom4j.io.SAXReader;   

import org.dom4j.io.XMLWriter;   

  

public class Dom4jModify   

{   

  public Document modifyDocument(File inputXml)   

  {   

    try  

    {   

      SAXReader saxReader = new SAXReader();   

      Document document = saxReader.read(inputXml);   

      document.addDocType("dbconfig",null,"db.dtd");   

      List list = document.content();   

  

      // Iterator iter = document.nodeIterator();   

      Iterator iter = list.iterator();   

  

      Element element = (Element) iter.next();   

      element.element("db").attribute("type").setValue("mysql");   

      element.element("db").element("url").setText("jdbc:mysql://localhost/mySql");   

      element.element("db").element("driver").setText("com.mysql.jdbc.Driver");   

      element.element("db").element("user").setText("root");   

      element.element("db").element("password").setText("xlc");   

         

      // 設(shè)置輸出格式   

      OutputFormat outFmt = new OutputFormat("    ", true);   

      outFmt.setEncoding("UTF-8");   

         

      XMLWriter xmlWriter=new XMLWriter(new FileWriter("domdb-modified.xml"),outFmt);   

      xmlWriter.write(document);   

      xmlWriter.flush();   

      xmlWriter.close();   

      return document;   

    }   

    catch (Exception e)   

    {   

      System.out.println(e.getMessage());   

      return null;   

    }   

  }   

  

  public static void main(String[] args) throws Exception   

  {   

    Dom4jModify dom4jParser = new Dom4jModify();   

    Document document = dom4jParser.modifyDocument(new File("domdb.xml"));   

       

    OutputFormat outFmt = new OutputFormat("    ", true);   

    outFmt.setEncoding("UTF-8");   

    XMLWriter xmlWriter = new XMLWriter(System.out,outFmt);   

    xmlWriter.write(document);   

xmlWriter.flush();   

xmlWriter.close();   

}   

}

上述內(nèi)容就是xml的四種解析方法及源代碼怎么寫,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

xml
AI