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

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;

sdk源碼查看路徑google code


創建和解析xml的效果圖:




2、Dom 創建 XML

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

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

Code

  1. /** Dom方式,創建 XML  */  
  2. public String domCreateXML() {  
  3.     String xmlWriter = null;  
  4.       
  5.     Person []persons = new Person[3];       // 創建節點Person對象   
  6.     persons[0] = new Person(1"sunboy_2050""http://blog.csdn.net/sunboy_2050");  
  7.     persons[1] = new Person(2"baidu""http://www.baidu.com");  
  8.     persons[2] = new Person(3"google""http://www.google.com");  
  9.       
  10.     try {  
  11.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  12.         DocumentBuilder builder = factory.newDocumentBuilder();  
  13.         Document doc = builder.newDocument();  
  14.           
  15.         Element eleRoot = doc.createElement("root");  
  16.         eleRoot.setAttribute("author""homer");  
  17.         eleRoot.setAttribute("date""2012-04-26");  
  18.         doc.appendChild(eleRoot);  
  19.           
  20.         int personsLen = persons.length;  
  21.         for(int i=0; i<personsLen; i++) {  
  22.             Element elePerson = doc.createElement("person");  
  23.             eleRoot.appendChild(elePerson);  
  24.               
  25.             Element eleId = doc.createElement("id");  
  26.             Node nodeId = doc.createTextNode(persons[i].getId() + "");  
  27.             eleId.appendChild(nodeId);  
  28.             elePerson.appendChild(eleId);  
  29.   
  30.             Element eleName = doc.createElement("name");  
  31.             Node nodeName = doc.createTextNode(persons[i].getName());  
  32.             eleName.appendChild(nodeName);  
  33.             elePerson.appendChild(eleName);  
  34.   
  35.             Element eleBlog = doc.createElement("blog");  
  36.             Node nodeBlog = doc.createTextNode(persons[i].getBlog());  
  37.             eleBlog.appendChild(nodeBlog);  
  38.             elePerson.appendChild(eleBlog);  
  39.         }  
  40.           
  41.           
  42.         Properties properties = new Properties();  
  43.         properties.setProperty(OutputKeys.INDENT, "yes");  
  44.         properties.setProperty(OutputKeys.MEDIA_TYPE, "xml");  
  45.         properties.setProperty(OutputKeys.VERSION, "1.0");  
  46.         properties.setProperty(OutputKeys.ENCODING, "utf-8");  
  47.         properties.setProperty(OutputKeys.METHOD, "xml");  
  48.         properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");  
  49.           
  50.         TransformerFactory transformerFactory = TransformerFactory.newInstance();  
  51.         Transformer transformer = transformerFactory.newTransformer();  
  52.         transformer.setOutputProperties(properties);  
  53.           
  54.         DOMSource domSource = new DOMSource(doc.getDocumentElement());  
  55.         OutputStream output = new ByteArrayOutputStream();  
  56.         StreamResult result = new StreamResult(output);  
  57.         transformer.transform(domSource, result);  
  58.           
  59.         xmlWriter = output.toString();  
  60.           
  61.     } catch (ParserConfigurationException e) {      // factory.newDocumentBuilder   
  62.         e.printStackTrace();  
  63.     } catch (DOMException e) {                      // doc.createElement   
  64.         e.printStackTrace();  
  65.     } catch (TransformerFactoryConfigurationError e) {      // TransformerFactory.newInstance   
  66.         e.printStackTrace();  
  67.     } catch (TransformerConfigurationException e) {     // transformerFactory.newTransformer   
  68.         e.printStackTrace();  
  69.     } catch (TransformerException e) {              // transformer.transform   
  70.         e.printStackTrace();  
  71.     } catch (Exception e) {  
  72.         e.printStackTrace();  
  73.     }  
  74.       
  75.     savedXML(fileName, xmlWriter.toString());  
  76.       
  77.     return xmlWriter.toString();  
  78. }  
	/** Dom方式,創建 XML  */
	public String domCreateXML() {
		String xmlWriter = null;
		
		Person []persons = new Person[3];		// 創建節點Person對象
		persons[0] = new Person(1, "sunboy_2050", "http://blog.csdn.net/sunboy_2050");
		persons[1] = new Person(2, "baidu", "http://www.baidu.com");
		persons[2] = new Person(3, "google", "http://www.google.com");
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.newDocument();
			
			Element eleRoot = doc.createElement("root");
			eleRoot.setAttribute("author", "homer");
			eleRoot.setAttribute("date", "2012-04-26");
			doc.appendChild(eleRoot);
			
			int personsLen = persons.length;
			for(int i=0; i<personsLen; i++) {
				Element elePerson = doc.createElement("person");
				eleRoot.appendChild(elePerson);
				
				Element eleId = doc.createElement("id");
				Node nodeId = doc.createTextNode(persons[i].getId() + "");
				eleId.appendChild(nodeId);
				elePerson.appendChild(eleId);

				Element eleName = doc.createElement("name");
				Node nodeName = doc.createTextNode(persons[i].getName());
				eleName.appendChild(nodeName);
				elePerson.appendChild(eleName);

				Element eleBlog = doc.createElement("blog");
				Node nodeBlog = doc.createTextNode(persons[i].getBlog());
				eleBlog.appendChild(nodeBlog);
				elePerson.appendChild(eleBlog);
			}
			
			
			Properties properties = new Properties();
			properties.setProperty(OutputKeys.INDENT, "yes");
			properties.setProperty(OutputKeys.MEDIA_TYPE, "xml");
			properties.setProperty(OutputKeys.VERSION, "1.0");
			properties.setProperty(OutputKeys.ENCODING, "utf-8");
			properties.setProperty(OutputKeys.METHOD, "xml");
			properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperties(properties);
			
			DOMSource domSource = new DOMSource(doc.getDocumentElement());
			OutputStream output = new ByteArrayOutputStream();
			StreamResult result = new StreamResult(output);
			transformer.transform(domSource, result);
			
			xmlWriter = output.toString();
			
		} catch (ParserConfigurationException e) {		// factory.newDocumentBuilder
			e.printStackTrace();
		} catch (DOMException e) {						// doc.createElement
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {		// TransformerFactory.newInstance
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {		// transformerFactory.newTransformer
			e.printStackTrace();
		} catch (TransformerException e) {				// transformer.transform
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		savedXML(fileName, xmlWriter.toString());
		
		return xmlWriter.toString();
	}

運行結果:





3、Dom 解析 XML

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

Code

  1. /** Dom方式,解析 XML  */  
  2. public String domResolveXML() {  
  3.     StringWriter xmlWriter = new StringWriter();  
  4.       
  5.     InputStream is= readXML(fileName);  
  6.     try {  
  7.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  8.         DocumentBuilder builder = factory.newDocumentBuilder();  
  9.         Document doc = builder.parse(is);  
  10.   
  11.         doc.getDocumentElement().normalize();  
  12.         NodeList nlRoot = doc.getElementsByTagName("root");  
  13.         Element eleRoot = (Element)nlRoot.item(0);  
  14.         String attrAuthor = eleRoot.getAttribute("author");  
  15.         String attrDate = eleRoot.getAttribute("date");  
  16.         xmlWriter.append("root").append("\t\t");  
  17.         xmlWriter.append(attrAuthor).append("\t");  
  18.         xmlWriter.append(attrDate).append("\n");  
  19.           
  20.         NodeList nlPerson = eleRoot.getElementsByTagName("person");  
  21.         int personsLen = nlPerson.getLength();  
  22.         Person []persons = new Person[personsLen];  
  23.         for(int i=0; i<personsLen; i++) {  
  24.             Element elePerson = (Element) nlPerson.item(i);     // person節點   
  25.             Person person = new Person();                       // 創建Person對象   
  26.               
  27.             NodeList nlId = elePerson.getElementsByTagName("id");  
  28.             Element eleId = (Element)nlId.item(0);  
  29.             String id = eleId.getChildNodes().item(0).getNodeValue();  
  30.             person.setId(Integer.parseInt(id));  
  31.               
  32.             NodeList nlName = elePerson.getElementsByTagName("name");  
  33.             Element eleName = (Element)nlName.item(0);  
  34.             String name = eleName.getChildNodes().item(0).getNodeValue();  
  35.             person.setName(name);  
  36.               
  37.             NodeList nlBlog = elePerson.getElementsByTagName("blog");  
  38.             Element eleBlog = (Element)nlBlog.item(0);  
  39.             String blog = eleBlog.getChildNodes().item(0).getNodeValue();  
  40.             person.setBlog(blog);  
  41.               
  42.             xmlWriter.append(person.toString()).append("\n");  
  43.             persons[i] = person;  
  44.         }  
  45.           
  46.     } catch (ParserConfigurationException e) {      // factory.newDocumentBuilder   
  47.         e.printStackTrace();  
  48.     } catch (SAXException e) {      // builder.parse   
  49.         e.printStackTrace();  
  50.     } catch (IOException e) {       // builder.parse   
  51.         e.printStackTrace();  
  52.     } catch (Exception e) {  
  53.         e.printStackTrace();  
  54.     }  
  55.       
  56.     return xmlWriter.toString();  
  57. }  
	/** Dom方式,解析 XML  */
	public String domResolveXML() {
		StringWriter xmlWriter = new StringWriter();
		
		InputStream is= readXML(fileName);
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(is);

			doc.getDocumentElement().normalize();
			NodeList nlRoot = doc.getElementsByTagName("root");
			Element eleRoot = (Element)nlRoot.item(0);
			String attrAuthor = eleRoot.getAttribute("author");
			String attrDate = eleRoot.getAttribute("date");
			xmlWriter.append("root").append("\t\t");
			xmlWriter.append(attrAuthor).append("\t");
			xmlWriter.append(attrDate).append("\n");
			
			NodeList nlPerson = eleRoot.getElementsByTagName("person");
			int personsLen = nlPerson.getLength();
			Person []persons = new Person[personsLen];
			for(int i=0; i<personsLen; i++) {
				Element elePerson = (Element) nlPerson.item(i);		// person節點
				Person person = new Person();						// 創建Person對象
				
				NodeList nlId = elePerson.getElementsByTagName("id");
				Element eleId = (Element)nlId.item(0);
				String id = eleId.getChildNodes().item(0).getNodeValue();
				person.setId(Integer.parseInt(id));
				
				NodeList nlName = elePerson.getElementsByTagName("name");
				Element eleName = (Element)nlName.item(0);
				String name = eleName.getChildNodes().item(0).getNodeValue();
				person.setName(name);
				
				NodeList nlBlog = elePerson.getElementsByTagName("blog");
				Element eleBlog = (Element)nlBlog.item(0);
				String blog = eleBlog.getChildNodes().item(0).getNodeValue();
				person.setBlog(blog);
				
				xmlWriter.append(person.toString()).append("\n");
				persons[i] = person;
			}
			
		} catch (ParserConfigurationException e) {		// factory.newDocumentBuilder
			e.printStackTrace();
		} catch (SAXException e) {		// builder.parse
			e.printStackTrace();
		} catch (IOException e) {		// builder.parse
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return xmlWriter.toString();
	}

運行結果:





4、Person類

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

  1. public class Person {  
  2.     private int id;  
  3.     private String name;  
  4.     private String blog;  
  5.       
  6.     public Person() {  
  7.         this.id = -1;  
  8.         this.name = "";  
  9.         this.blog = "";  
  10.     }  
  11.   
  12.     public Person(int id, String name, String blog) {  
  13.         this.id = id;  
  14.         this.name = name;  
  15.         this.blog = blog;  
  16.     }  
  17.       
  18.     public Person(Person person) {  
  19.         this.id = person.id;  
  20.         this.name = person.name;  
  21.         this.blog = person.blog;  
  22.     }  
  23.   
  24.     public Person getPerson(){  
  25.         return this;  
  26.     }  
  27.       
  28.     public void setId(int id) {  
  29.         this.id = id;  
  30.     }  
  31.       
  32.     public int getId(){  
  33.         return this.id;  
  34.     }  
  35.       
  36.     public void setName(String name) {  
  37.         this.name = name;  
  38.     }  
  39.   
  40.     public String getName() {  
  41.         return this.name;  
  42.     }  
  43.   
  44.     public void setBlog(String blog) {  
  45.         this.blog = blog;  
  46.     }  
  47.   
  48.     public String getBlog() {  
  49.         return this.blog;  
  50.     }  
  51.   
  52.     public String toString() {  
  53.         return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n";  
  54.     }  
  55. }  
public class Person {
	private int id;
	private String name;
	private String blog;
	
	public Person() {
		this.id = -1;
		this.name = "";
		this.blog = "";
	}

	public Person(int id, String name, String blog) {
		this.id = id;
		this.name = name;
		this.blog = blog;
	}
	
	public Person(Person person) {
		this.id = person.id;
		this.name = person.name;
		this.blog = person.blog;
	}

	public Person getPerson(){
		return this;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public int getId(){
		return this.id;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setBlog(String blog) {
		this.blog = blog;
	}

	public String getBlog() {
		return this.blog;
	}

	public String toString() {
		return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n";
	}
}



代碼下載



參考推薦:

org.w3c.dom

javax.xml.parsers

javax.xml.transform


dom創建xml

java dom創建xml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章