码迷,mamicode.com
首页 > 其他好文 > 详细

读写XML

时间:2014-08-08 02:02:25      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:xml   java   dom   

XML是一种可扩展标记语言

下面是一个完整的XML文件(也是下文介绍读写XML的样本):

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <poem author="William Carlos Williams" title="The Great Figure">  
  3.     <line>Among the rain</line>  
  4.     <line>and ligths</line>  
  5.     <line>I saw the figure 5</line>  
  6.     <line>in gold</line>  
  7.     <line>on a red</line>  
  8.     <line>fire truck</line>  
  9.     <line>moving</line>  
  10.     <line>tense</line>  
  11.     <line>unheeded</line>  
  12.     <line>to gong clangs</line>  
  13.     <line>siren howls</line>  
  14.     <line>and wheels rumbling</line>  
  15.     <line>through the dark city</line>  
  16. </poem>  


一、写XML

本文介绍两种方式:使用DOM开发包来写XML文件和用String对象的方式

将Poem类作为数据源,提供需要转换成XML的内容:

[java] view plaincopy
  1. class Poem {  
  2.     private static String title = "The Great Figure";  
  3.     private static String author = "William Carlos Williams";  
  4.     private static ArrayList<String> lines = new ArrayList<String>();  
  5.     static {  
  6.         lines.add("Among the rain");  
  7.         lines.add("and ligths");  
  8.         lines.add("I saw the figure 5");  
  9.         lines.add("in gold");  
  10.         lines.add("on a red");  
  11.         lines.add("fire truck");  
  12.         lines.add("moving");  
  13.         lines.add("tense");  
  14.         lines.add("unheeded");  
  15.         lines.add("to gong clangs");  
  16.         lines.add("siren howls");  
  17.         lines.add("and wheels rumbling");  
  18.         lines.add("through the dark city");  
  19.     }  
  20.     public static String getTitle() {  
  21.         return title;  
  22.     }  
  23.     public static String getAuthor() {  
  24.         return author;  
  25.     }  
  26.     public static ArrayList<String> getLines() {  
  27.         return lines;  
  28.     }  
  29. }  


1、用DOM写XML文件

流程:

(1)创建一个空的Document对象(最顶层的DOM对象,包含了创建XML所需要的其他一切)。

(2)创建元素和属性,把元素和属性加到Document对象中。

(3)把Document对象的内容转换成String对象。

(4)把String对象写到目标文件里去。

[java] view plaincopy
  1. import java.util.ArrayList;  
  2. import java.io.*;  
  3. import javax.xml.parsers.*;  
  4. import javax.xml.transform.*;  
  5. import javax.xml.transform.dom.DOMSource;  
  6. import javax.xml.transform.stream.StreamResult;  
  7. import org.w3c.dom.*;  
  8.   
  9. public class XmlTest {  
  10.     public static void main(String[] args) {  
  11.         Document doc = createXMLContent1(); // 创建空文档  
  12.         createElements(doc); // 创建XML  
  13.         String xmlContent = createXMLString(doc);// 创建字符串以表示XML  
  14.         writeXMLToFile1(xmlContent);  
  15.     }  
  16.   
  17.     /*********** 用DOM写XML文件 ***********/  
  18.     private static Document createXMLContent1() {  
  19.         Document doc = null;  
  20.         try {  
  21.             // 使应用程序能够从XML文档获取生成 DOM 对象树的解析器  
  22.             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
  23.             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
  24.             doc = docBuilder.newDocument();  
  25.             // 作为 XML 声明 的一部分指定此文档是否是单独的的属性。未指定时,此属性为 false。  
  26.             doc.setXmlStandalone(true);  
  27.         } catch (ParserConfigurationException pce) {  
  28.             System.out.println("Couldn‘t create a DocumentBuilder");  
  29.             System.exit(1);  
  30.         }  
  31.         return doc;  
  32.     }  
  33.     private static void createElements(Document doc) {  
  34.         // 创建根元素  
  35.         Element poem = doc.createElement("poem");  
  36.         poem.setAttribute("title", Poem.getTitle());  
  37.         poem.setAttribute("author", Poem.getAuthor());  
  38.         // 把根元素加到文档里去  
  39.         doc.appendChild(poem);  
  40.         // 创建子元素  
  41.         for (String lineIn : Poem.getLines()) {  
  42.             Element line = doc.createElement("line");  
  43.             Text lineText = doc.createTextNode(lineIn);  
  44.             line.appendChild(lineText);  
  45.             // 把每个元素加到根元素里去  
  46.             poem.appendChild(line);  
  47.         }  
  48.     }  
  49.     private static String createXMLString(Document doc) {  
  50.         // 将DOM转换成字符串  
  51.         Transformer transformer = null;  
  52.         StringWriter stringWriter = new StringWriter();  
  53.         try {  
  54.             TransformerFactory transformerFactory = TransformerFactory.newInstance();  
  55.             transformer = transformerFactory.newTransformer();  
  56.             // 是否应输出 XML 声明  
  57.             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");  
  58.             // 是否以XML格式自动换行  
  59.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  60.             // 创建字符串以包含XML  
  61.             stringWriter = new StringWriter();  
  62.             StreamResult result = new StreamResult(stringWriter);// 充当转换结果的持有者  
  63.             DOMSource source = new DOMSource(doc);  
  64.             transformer.transform(source, result);  
  65.         } catch (TransformerConfigurationException e) {  
  66.             System.out.println("Couldn‘t create a Transformer");  
  67.             System.exit(1);  
  68.         } catch (TransformerException e) {  
  69.             System.out.println("Couldn‘t transforme DOM to a String");  
  70.             System.exit(1);  
  71.         }  
  72.         return stringWriter.toString();  
  73.     }  
  74.     private static void writeXMLToFile1(String xmlContent) {  
  75.         String fileName = "E:\\test\\domoutput.xml";  
  76.         try {  
  77.             File domOutput = new File(fileName);  
  78.             FileOutputStream domOutputStream = new FileOutputStream(domOutput);  
  79.             domOutputStream.write(xmlContent.getBytes());  
  80.             domOutputStream.close();  
  81.             System.out.println(fileName + " was successfully written");  
  82.         } catch (FileNotFoundException e) {  
  83.             System.out.println("Couldn‘t find a file called" + fileName);  
  84.             System.exit(1);  
  85.         } catch (IOException e) {  
  86.             System.out.println("Couldn‘t write a file called" + fileName);  
  87.             System.exit(1);  
  88.         }  
  89.     }  


2、用String写XML文件

这种方法就比较简单,就是直接用字符串把整个XML文件描述出来,然后保存文件。


二、读取XML文件

两种方式:用DOM读取XML文件和用SAX方式。一般DOM处理内容比较小的XML文件,而SAX可以处理任意大小的XML文件。


1、用DOM读取XML文件

[java] view plaincopy
  1. public class XmlTest {  
  2.     public static void main(String[] args) {  
  3.         String fileName = "E:\\test\\domoutput.xml";  
  4.         writeFileContentsToConsole(fileName);  
  5.     }  
  6.     /*********** 用DOM读取XML文件 ***********/  
  7.     private static void writeFileContentsToConsole(String fileName) {  
  8.         Document doc = createDocument(fileName);  
  9.         Element root = doc.getDocumentElement();// 获取根元素  
  10.         StringBuilder sb = new StringBuilder();  
  11.         sb.append("The root element is named:\"" + root.getNodeName() + "\"");  
  12.         sb.append("and has the following attributes: ");  
  13.         NamedNodeMap attributes = root.getAttributes();  
  14.         for (int i = 0; i < attributes.getLength(); i++) {  
  15.             Node thisAttribute = attributes.item(i);  
  16.             sb.append(thisAttribute.getNodeName());  
  17.             sb.append("(\"" + thisAttribute.getNodeValue() + "\")");  
  18.             if (i < attributes.getLength() - 1) {  
  19.                 sb.append(",");  
  20.             }  
  21.         }  
  22.         System.out.println(sb);// 根元素的描述信息  
  23.         NodeList nodes = doc.getElementsByTagName("line");  
  24.         for (int i = 0; i < nodes.getLength(); i++) {  
  25.             Element element = (Element) nodes.item(i);  
  26.             System.out.println("Found an element named \""  
  27.                     + element.getTagName() + "\""  
  28.                     + "With the following content: \""  
  29.                     + element.getTextContent() + "\"");  
  30.         }  
  31.     }  
  32.     private static Document createDocument(String fileName) {// 从文件创建DOM的Document对象  
  33.         Document doc = null;  
  34.         try {  
  35.             File xmlFile = new File(fileName);  
  36.             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();  
  37.             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();  
  38.             doc = docBuilder.parse(xmlFile);// 解析xml文件加载为dom文档  
  39.             doc.setXmlStandalone(true);  
  40.         } catch (IOException e) {  
  41.             e.printStackTrace();  
  42.         } catch (SAXException e) {  
  43.             e.printStackTrace();  
  44.         } catch (ParserConfigurationException e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.         return doc;  
  48.     }  
  49. }/*   
  50.  * Output: 
  51.  * The root element is named:"poem"and has the following attributes: author("William Carlos Williams"),title("The Great Figure") 
  52.  * Found an element named "line"With the following content: "Among the rain" 
  53.  * Found an element named "line"With the following content: "and ligths" 
  54.  * ... ...  
  55.  */// :~   


2、用SAX读取XML文件

SAX是使用ContentHandler接口来公开解析事件,而且SAX包提供了一个默认实现类DefaultHandler,它的默认行为就是什么都不做。下面就通过XMLToConsoleHandler类来覆盖其中的一些方法,来捕获XML文件的内容。

[java] view plaincopy
  1. import org.w3c.dom.CharacterData;  
  2. import org.xml.sax.SAXException;  
  3. import org.xml.sax.helpers.DefaultHandler;  
  4. public class XmlTest {  
  5.     public static void main(String[] args) {  
  6.         String fileName = "E:\\test\\domoutput.xml";  
  7.         getFileContents(fileName);  
  8.     }  
  9.     private static void getFileContents(String fileName) {  
  10.         try {  
  11.             XMLToConsoleHandler handler = new XMLToConsoleHandler();  
  12.             SAXParserFactory factory = SAXParserFactory.newInstance();  
  13.             SAXParser saxParser = factory.newSAXParser();  
  14.             saxParser.parse(fileName, handler);  
  15.         } catch (IOException e) {  
  16.             e.printStackTrace();  
  17.         } catch (ParserConfigurationException e) {  
  18.             e.printStackTrace();  
  19.         } catch (SAXException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23. }  
  24. /***********  用SAX读取XML文件   ***********/     
  25. class XMLToConsoleHandler extends DefaultHandler {  
  26.     public void characters(char[] content, int start, int length)  
  27.             throws SAXException { // 处理元素的真正内容  
  28.             System.out.println("Found content: " + new String(content, start, length));  
  29.     }  
  30.     public void endElement(String arg0, String localName, String qName)throws SAXException {  
  31.         System.out.println("Found the end of an element named \"" + qName + "\"");  
  32.     }  
  33.     public void startElement(String uri, String localName, String qName,  
  34.             Attributes attributes) throws SAXException {  
  35.         StringBuilder sb = new StringBuilder();  
  36.         sb.append("Found the start of an element named \"" + qName + "\"");  
  37.         if (attributes != null && attributes.getLength() > 0) {  
  38.             sb.append(" with attributes named ");  
  39.             for (int i = 0; i < attributes.getLength(); i++) {  
  40.                 String attributeName = attributes.getLocalName(i);  
  41.                 String attributeValue = attributes.getValue(i);  
  42.                 sb.append("\"" + attributeName + "\"");  
  43.                 sb.append(" (value = ");  
  44.                 sb.append("\"" + attributeValue + "\"");  
  45.                 sb.append(")");  
  46.                 if (i < attributes.getLength() - 1) {  
  47.                     sb.append(",");  
  48.                 }  
  49.             }  
  50.         }  
  51.         System.out.println(sb.toString());  
  52.     }  
  53. }  

读写XML,布布扣,bubuko.com

读写XML

标签:xml   java   dom   

原文地址:http://blog.csdn.net/goluck98/article/details/38428087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!