Java解析XML(二)、DOM

來源:互聯網
上載者:User

XML資源檔請見http://blog.csdn.net/xyang81/article/details/7247169

package xml;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Result;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import model.Book;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import util.DateUtils;/** * 使用DOM讀寫XML * @author 楊信 * */public class DomHelper {private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();/** * 使用DOM解析XML * @param is XML檔案輸入資料流 * @return 解析後的資料 */public static List<Book> domReader(InputStream is) {List<Book> books = null;try {DocumentBuilder db = dbf.newDocumentBuilder();Document document = db.parse(is);Element rootElement = document.getDocumentElement();NodeList nodes = rootElement.getElementsByTagName("book");if (nodes != null && nodes.getLength() > 0) {books = new ArrayList<Book>();for(int i = 0; i < nodes.getLength(); i++) {/*//獲得節點方式1Node node = nodes.item(i);book.setIsbn(node.getAttributes().item(0).getNodeValue());//獲得book節點ISBN屬性的值//獲得book節點下的所有子節點NodeList bookChildList = node.getChildNodes();*///獲得節點方式2Book book = new Book();Element bookElement = (Element) nodes.item(i);book.setIsbn(bookElement.getAttribute("isbn"));//獲得book節點ISBN屬性的值NodeList bookChildList = bookElement.getChildNodes();for(int j = 0; j < bookChildList.getLength(); j++) {Node childNode = bookChildList.item(j);if (childNode.getNodeType() == Node.ELEMENT_NODE) {//判斷當前節點類型,是否為一個元素節點.(節點類型分:Element和Text節點.)String nodeName = childNode.getNodeName();String nodeValue = childNode.getTextContent();if ("name".equals(nodeName)) {book.setName(nodeValue);} else if ("author".equals(nodeName)) {book.setAuthor(nodeValue);} else if ("publishing".equals(nodeName)) {book.setPublishing(nodeValue);} else if ("pubdate".equals(nodeName)) {book.setPubdate(DateUtils.string2Date("yyyy-mm-dd", nodeValue));} else if ("price".equals(nodeName)) {book.setPrice(Double.parseDouble(nodeValue));}}}books.add(book);}}} catch (Exception e) {e.printStackTrace();} finally {try {is.close();} catch (IOException e) {e.printStackTrace();}}return books;}/** * 使用dom寫xml檔案 * @param books 資料 * @param outfile xml檔案儲存位置 */public static void domWriter(List<Book> books,File outfile) {Document doc = null;try {DocumentBuilder db = dbf.newDocumentBuilder();doc = db.newDocument();Element booksElement = doc.createElement("books");for (Book book : books) {//建立一本圖書Element bookElement = doc.createElement("book");//設定圖片的編號bookElement.setAttribute("isbn", book.getIsbn());//書名Element nameElement = doc.createElement("name");nameElement.setTextContent(book.getName());bookElement.appendChild(nameElement);//作者Element authorElement = doc.createElement("author");authorElement.setTextContent(book.getAuthor());bookElement.appendChild(authorElement);//出版社Element publishingElement = doc.createElement("publishing");publishingElement.setTextContent(book.getPublishing());bookElement.appendChild(publishingElement);//出版日期Element pubdateElement = doc.createElement("pubdate");pubdateElement.setTextContent(DateUtils.date2String("yyyy-mm-dd", book.getPubdate()));bookElement.appendChild(pubdateElement);//價格Element priceElement = doc.createElement("price");priceElement.setTextContent(String.valueOf(book.getPrice()));bookElement.appendChild(priceElement);//將每本書添加到根節點中booksElement.appendChild(bookElement);}doc.appendChild(booksElement);//將資料產生xml檔案FileOutputStream fos = new FileOutputStream(outfile);OutputStreamWriter outwriter = new OutputStreamWriter(fos);callWriteXmlFile(doc, outwriter, "gb2312");outwriter.close();fos.close();} catch (Exception e) {e.printStackTrace();}}/** * 定入xml檔案 * @param doc xml文檔對象 * @param w 寫xml檔案的字元流對象 * @param encoding xml編碼 */public static void callWriteXmlFile(Document doc, Writer w, String encoding) {try {Source source = new DOMSource(doc);Result result = new StreamResult(w);Transformer xformer = TransformerFactory.newInstance().newTransformer();xformer.setOutputProperty(OutputKeys.ENCODING, encoding);xformer.transform(source, result);} catch (TransformerConfigurationException e) {e.printStackTrace();} catch (TransformerException e) {e.printStackTrace();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.