JAVA學習筆記 -- 讀寫XML

來源:互聯網
上載者:User

標籤:ack   catch   通過   cat   false   字元   元素   定時   ons   

XML是一種可延伸標記語言 (XML)

以下是一個完整的XML檔案(也是下文介紹讀寫XML的樣本):

<?

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

><poem author="William Carlos Williams" title="The Great Figure"><line>Among the rain</line><line>and ligths</line><line>I saw the figure 5</line><line>in gold</line><line>on a red</line><line>fire truck</line><line>moving</line><line>tense</line><line>unheeded</line><line>to gong clangs</line><line>siren howls</line><line>and wheels rumbling</line><line>through the dark city</line></poem>


一、寫XML

本文介紹兩種方式:使用DOM開發包來寫XML檔案和用String對象的方式

將Poem類作為資料來源,提供須要轉換成XML的內容:

class Poem {private static String title = "The Great Figure";private static String author = "William Carlos Williams";private static ArrayList<String> lines = new ArrayList<String>();static {lines.add("Among the rain");lines.add("and ligths");lines.add("I saw the figure 5");lines.add("in gold");lines.add("on a red");lines.add("fire truck");lines.add("moving");lines.add("tense");lines.add("unheeded");lines.add("to gong clangs");lines.add("siren howls");lines.add("and wheels rumbling");lines.add("through the dark city");}public static String getTitle() {return title;}public static String getAuthor() {return author;}public static ArrayList<String> getLines() {return lines;}}


1、用DOM寫XML檔案

流程:

(1)建立一個空的Document對象(最頂層的DOM對象,包括了建立XML所須要的其它一切)。

(2)建立元素和屬性,把元素和屬性加到Document對象中。

(3)把Document對象的內容轉換成String對象。

(4)把String對象寫到目標檔案中去。

import java.util.ArrayList;import java.io.*;import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.*;public class XmlTest {public static void main(String[] args) {Document doc = createXMLContent1(); // 建立空文檔createElements(doc); // 建立XMLString xmlContent = createXMLString(doc);// 建立字串以表示XMLwriteXMLToFile1(xmlContent);}/*********** 用DOM寫XML檔案 ***********/private static Document createXMLContent1() {Document doc = null;try {// 使應用程式可以從XML文檔擷取產生 DOM 對象樹的解析器DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();DocumentBuilder docBuilder = dbfac.newDocumentBuilder();doc = docBuilder.newDocument();// 作為 XML 聲明 的一部分指定此文檔是否是單獨的的屬性。

未指定時,此屬性為 false。doc.setXmlStandalone(true);} catch (ParserConfigurationException pce) {System.out.println("Couldn‘t create a DocumentBuilder");System.exit(1);}return doc;}private static void createElements(Document doc) {// 建立根項目Element poem = doc.createElement("poem");poem.setAttribute("title", Poem.getTitle());poem.setAttribute("author", Poem.getAuthor());// 把根項目加到文檔裡去doc.appendChild(poem);// 建立子項目for (String lineIn : Poem.getLines()) {Element line = doc.createElement("line");Text lineText = doc.createTextNode(lineIn);line.appendChild(lineText);// 把每一個元素加到根項目裡去poem.appendChild(line);}}private static String createXMLString(Document doc) {// 將DOM轉換成字串Transformer transformer = null;StringWriter stringWriter = new StringWriter();try {TransformerFactory transformerFactory = TransformerFactory.newInstance();transformer = transformerFactory.newTransformer();// 是否應輸出 XML 聲明transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");// 是否以XML格式自己主動換行transformer.setOutputProperty(OutputKeys.INDENT, "yes");// 建立字串以包括XMLstringWriter = new StringWriter();StreamResult result = new StreamResult(stringWriter);// 充當轉換結果的持有人DOMSource source = new DOMSource(doc);transformer.transform(source, result);} catch (TransformerConfigurationException e) {System.out.println("Couldn‘t create a Transformer");System.exit(1);} catch (TransformerException e) {System.out.println("Couldn‘t transforme DOM to a String");System.exit(1);}return stringWriter.toString();}private static void writeXMLToFile1(String xmlContent) {String fileName = "E:\\test\\domoutput.xml";try {File domOutput = new File(fileName);FileOutputStream domOutputStream = new FileOutputStream(domOutput);domOutputStream.write(xmlContent.getBytes());domOutputStream.close();System.out.println(fileName + " was successfully written");} catch (FileNotFoundException e) {System.out.println("Couldn‘t find a file called" + fileName);System.exit(1);} catch (IOException e) {System.out.println("Couldn‘t write a file called" + fileName);System.exit(1);}}


2、用String寫XML檔案

這樣的方法就比較簡單。就是直接用字串把整個XML檔案描寫敘述出來,然後儲存檔案。


二、讀取XML檔案

兩種方式:用DOM讀取XML檔案和用SAX方式。一般DOM處理內容比較小的XML檔案。而SAX能夠處理隨意大小的XML檔案。


1、用DOM讀取XML檔案

public class XmlTest {public static void main(String[] args) {String fileName = "E:\\test\\domoutput.xml";writeFileContentsToConsole(fileName);}/*********** 用DOM讀取XML檔案 ***********/private static void writeFileContentsToConsole(String fileName) {Document doc = createDocument(fileName);Element root = doc.getDocumentElement();// 擷取根項目StringBuilder sb = new StringBuilder();sb.append("The root element is named:\"" + root.getNodeName() + "\"");sb.append("and has the following attributes: ");NamedNodeMap attributes = root.getAttributes();for (int i = 0; i < attributes.getLength(); i++) {Node thisAttribute = attributes.item(i);sb.append(thisAttribute.getNodeName());sb.append("(\"" + thisAttribute.getNodeValue() + "\")");if (i < attributes.getLength() - 1) {sb.append(",");}}System.out.println(sb);// 根項目的描寫敘述資訊NodeList nodes = doc.getElementsByTagName("line");for (int i = 0; i < nodes.getLength(); i++) {Element element = (Element) nodes.item(i);System.out.println("Found an element named \""+ element.getTagName() + "\""+ "With the following content: \""+ element.getTextContent() + "\"");}}private static Document createDocument(String fileName) {// 從檔案建立DOM的Document對象Document doc = null;try {File xmlFile = new File(fileName);DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();DocumentBuilder docBuilder = dbfac.newDocumentBuilder();doc = docBuilder.parse(xmlFile);// 解析xml檔案載入為dom文檔doc.setXmlStandalone(true);} catch (IOException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();}return doc;}}/*   * Output: * The root element is named:"poem"and has the following attributes: author("William Carlos Williams"),title("The Great Figure") * Found an element named "line"With the following content: "Among the rain" * Found an element named "line"With the following content: "and ligths" * ... ...  */// :~ 


2、用SAX讀取XML檔案

SAX是使用ContentHandler介面來公開解析事件,並且SAX包提供了一個預設實作類別DefaultHandler,它的預設行為就是什麼都不做。以下就通過XMLToConsoleHandler類來覆蓋當中的一些方法,來捕獲XML檔案的內容。

import org.w3c.dom.CharacterData;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class XmlTest {public static void main(String[] args) {String fileName = "E:\\test\\domoutput.xml";getFileContents(fileName);}private static void getFileContents(String fileName) {try {XMLToConsoleHandler handler = new XMLToConsoleHandler();SAXParserFactory factory = SAXParserFactory.newInstance();SAXParser saxParser = factory.newSAXParser();saxParser.parse(fileName, handler);} catch (IOException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();}}}/***********  用SAX讀取XML檔案   ***********/   class XMLToConsoleHandler extends DefaultHandler {public void characters(char[] content, int start, int length)throws SAXException { // 處理元素的真正內容System.out.println("Found content: " + new String(content, start, length));}public void endElement(String arg0, String localName, String qName)throws SAXException {System.out.println("Found the end of an element named \"" + qName + "\"");}public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {StringBuilder sb = new StringBuilder();sb.append("Found the start of an element named \"" + qName + "\"");if (attributes != null && attributes.getLength() > 0) {sb.append(" with attributes named ");for (int i = 0; i < attributes.getLength(); i++) {String attributeName = attributes.getLocalName(i);String attributeValue = attributes.getValue(i);sb.append("\"" + attributeName + "\"");sb.append(" (value = ");sb.append("\"" + attributeValue + "\"");sb.append(")");if (i < attributes.getLength() - 1) {sb.append(",");}}}System.out.println(sb.toString());}}









JAVA學習筆記 -- 讀寫XML

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.