Android creation and parsing XML (ii)--detailed DOM approach _android

Source: Internet
Author: User

1. Dom Overview

Dom to create XML, you apply the standard XML constructor javax.xml.parsers.DocumentBuilder to create XML documents, you need to import the following

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;

Create and parse an effect diagram for XML:

2. Dom creates XML

Dom, you can create Org.w3c.dom.Document objects by using Javax.xml.parsers.DocumentBuilder.

Use the Documentbuilder object from Documentbuilderfactory to create and parse XML documents on the Android device. You will use an extension of the XML pull parser to parse the XML document.

/** Dom method, create XML/Public String Domcreatexml () {string xmlWriter = null;    person []persons = new person[3]; 
  Create node Person object 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 (); 
 }

Run Result:

3. Dom parsing XML

Dom Way, parsing XML is the inverse process of creating XML, mainly using Builder.parse (IS) to parse, and then get element and node properties or values through tag, nodelist, element, childnotes, etc.

/** Dom method, parse 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 Node Person PErson = new Person (); 
      Create a Person object 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; 
  The catch (Parserconfigurationexception e) {//Factorynewdocumentbuilder eprintstacktrace (); 
  catch (Saxexception e) {//Builderparse eprintstacktrace (); catch (IOException e) {   Builderparse Eprintstacktrace (); 
  catch (Exception e) {eprintstacktrace (); 
return xmlwritertostring (); 

 }

Run Result:

4, Person class

The person class, which is a unit instance of creating XML, a class based on Java object-oriented definition

 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; 
    (person person) {thisid = PersonID; 
    Thisname = PersonName; 
  Thisblog = Personblog; 
  Public Person Getperson () {return this; 
  The 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 '; } 
} 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.