Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android創建與解析XML(二)——詳解Dom方式

Android創建與解析XML(二)——詳解Dom方式

編輯:關於Android編程

1. Dom概述

Dom方式創建XML,應用了標准xml構造器 javax.xml.parsers.DocumentBuilder 來創建 XML 文檔,需要導入以下內容

javax.xml.parsers

javax.xml.parsers.DocumentBuilder 

javax.xml.parsers.DocumentBuilderFactory 

javax.xml.parsers.ParserConfigurationException;
javax.xml.transform

javax.xml.transform.TransformerFactory 

javax.xml.transform.Transformer 

javax.xml.transform.dom.DOMSource 

javax.xml.transform.stream.StreamResult 

javax.xml.transform.OutputKeys;

javax.xml.transform.TransformerFactoryConfigurationError;

javax.xml.transform.TransformerConfigurationException;

javax.xml.transform.TransformerException;

org.w3c.dom 

org.w3c.dom.Document;

org.w3c.dom.Element;

org.w3c.dom.Node;

org.w3c.dom.DOMException;

org.w3c.dom.NodeList;

org.xml.sax.SAXException;

創建和解析xml的效果圖:

2、Dom 創建 XML

Dom,借助 javax.xml.parsers.DocumentBuilder,可以創建 org.w3c.dom.Document 對象。

使用來自 DocumentBuilderFactory 的 DocumentBuilder 對象在 Android 設備上創建與解析 XML 文檔。您將使用 XML pull 解析器的擴展來解析 XML 文檔。

/** Dom方式,創建 XML */ 
public String domCreateXML() { 
  String xmlWriter = null; 
   
  Person []persons = new Person[3];    // 創建節點Person對象 
  persons[0] = new Person(1, "sunboy_2050", "http://www.jb51.net/"); 
  persons[1] = new Person(2, "baidu", "http://wwwbaiducom"); 
  persons[2] = new Person(3, "google", "http://wwwgooglecom"); 
   
  try { 
    DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); 
    DocumentBuilder builder = factorynewDocumentBuilder(); 
    Document doc = buildernewDocument(); 
     
    Element eleRoot = doccreateElement("root"); 
    eleRootsetAttribute("author", "homer"); 
    eleRootsetAttribute("date", "2012-04-26"); 
    docappendChild(eleRoot); 
     
    int personsLen = personslength; 
    for(int i=0; i<personsLen; i++) { 
      Element elePerson = doccreateElement("person"); 
      eleRootappendChild(elePerson); 
       
      Element eleId = doccreateElement("id"); 
      Node nodeId = doccreateTextNode(persons[i]getId() + ""); 
      eleIdappendChild(nodeId); 
      elePersonappendChild(eleId); 
 
      Element eleName = doccreateElement("name"); 
      Node nodeName = doccreateTextNode(persons[i]getName()); 
      eleNameappendChild(nodeName); 
      elePersonappendChild(eleName); 
 
      Element eleBlog = doccreateElement("blog"); 
      Node nodeBlog = doccreateTextNode(persons[i]getBlog()); 
      eleBlogappendChild(nodeBlog); 
      elePersonappendChild(eleBlog); 
    } 
     
     
    Properties properties = new Properties(); 
    propertiessetProperty(OutputKeysINDENT, "yes"); 
    propertiessetProperty(OutputKeysMEDIA_TYPE, "xml"); 
    propertiessetProperty(OutputKeysVERSION, "0"); 
    propertiessetProperty(OutputKeysENCODING, "utf-8"); 
    propertiessetProperty(OutputKeysMETHOD, "xml"); 
    propertiessetProperty(OutputKeysOMIT_XML_DECLARATION, "yes"); 
     
    TransformerFactory transformerFactory = TransformerFactorynewInstance(); 
    Transformer transformer = transformerFactorynewTransformer(); 
    transformersetOutputProperties(properties); 
     
    DOMSource domSource = new DOMSource(docgetDocumentElement()); 
    OutputStream output = new ByteArrayOutputStream(); 
    StreamResult result = new StreamResult(output); 
    transformertransform(domSource, result); 
     
    xmlWriter = outputtoString(); 
     
  } catch (ParserConfigurationException e) {   // factorynewDocumentBuilder 
    eprintStackTrace(); 
  } catch (DOMException e) {           // doccreateElement 
    eprintStackTrace(); 
  } catch (TransformerFactoryConfigurationError e) {   // TransformerFactorynewInstance 
    eprintStackTrace(); 
  } catch (TransformerConfigurationException e) {   // transformerFactorynewTransformer 
    eprintStackTrace(); 
  } catch (TransformerException e) {       // transformertransform 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  savedXML(fileName, xmlWritertoString()); 
   
  return xmlWritertoString(); 
} 

運行結果:

3、Dom 解析 XML

Dom方式,解析XML是創建XML的逆過程,主要用到了builder.parse(is)進行解析,然後通過Tag、NodeList、Element、childNotes等得到Element和Node屬性或值。

/** Dom方式,解析 XML */ 
public String domResolveXML() { 
  StringWriter xmlWriter = new StringWriter(); 
   
  InputStream is= readXML(fileName); 
  try { 
    DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); 
    DocumentBuilder builder = factorynewDocumentBuilder(); 
    Document doc = builderparse(is); 
 
    docgetDocumentElement()normalize(); 
    NodeList nlRoot = docgetElementsByTagName("root"); 
    Element eleRoot = (Element)nlRootitem(0); 
    String attrAuthor = eleRootgetAttribute("author"); 
    String attrDate = eleRootgetAttribute("date"); 
    xmlWriterappend("root")append("\t\t"); 
    xmlWriterappend(attrAuthor)append("\t"); 
    xmlWriterappend(attrDate)append("\n"); 
     
    NodeList nlPerson = eleRootgetElementsByTagName("person"); 
    int personsLen = nlPersongetLength(); 
    Person []persons = new Person[personsLen]; 
    for(int i=0; i<personsLen; i++) { 
      Element elePerson = (Element) nlPersonitem(i);   // person節點 
      Person person = new Person();            // 創建Person對象 
       
      NodeList nlId = elePersongetElementsByTagName("id"); 
      Element eleId = (Element)nlIditem(0); 
      String id = eleIdgetChildNodes()item(0)getNodeValue(); 
      personsetId(IntegerparseInt(id)); 
       
      NodeList nlName = elePersongetElementsByTagName("name"); 
      Element eleName = (Element)nlNameitem(0); 
      String name = eleNamegetChildNodes()item(0)getNodeValue(); 
      personsetName(name); 
       
      NodeList nlBlog = elePersongetElementsByTagName("blog"); 
      Element eleBlog = (Element)nlBlogitem(0); 
      String blog = eleBloggetChildNodes()item(0)getNodeValue(); 
      personsetBlog(blog); 
       
      xmlWriterappend(persontoString())append("\n"); 
      persons[i] = person; 
    } 
     
  } catch (ParserConfigurationException e) {   // factorynewDocumentBuilder 
    eprintStackTrace(); 
  } catch (SAXException e) {   // builderparse 
    eprintStackTrace(); 
  } catch (IOException e) {    // builderparse 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  return xmlWritertoString(); 
} 

運行結果:

4、Person類

Person類,是創建xml的單位實例,基於Java面向對象定義的一個類

public class Person { 
  private int id; 
  private String name; 
  private String blog; 
   
  public Person() { 
    thisid = -1; 
    thisname = ""; 
    thisblog = ""; 
  } 
 
  public Person(int id, String name, String blog) { 
    thisid = id; 
    thisname = name; 
    thisblog = blog; 
  } 
   
  public Person(Person person) { 
    thisid = personid; 
    thisname = personname; 
    thisblog = personblog; 
  } 
 
  public Person getPerson(){ 
    return this; 
  } 
   
  public void setId(int id) { 
    thisid = id; 
  } 
   
  public int getId(){ 
    return thisid; 
  } 
   
  public void setName(String name) { 
    thisname = name; 
  } 
 
  public String getName() { 
    return thisname; 
  } 
 
  public void setBlog(String blog) { 
    thisblog = blog; 
  } 
 
  public String getBlog() { 
    return thisblog; 
  } 
 
  public String toString() { 
    return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n"; 
  } 
} 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved