您想學習如何從java讀寫XML文件嗎?
XML文件用於各種目的,包括存儲數據。在JSON流行之前,XML是表示、存儲和傳輸結構化數據的首選格式。儘管近年來XML的流行程度有所下降,但您可能偶爾會遇到它,因此從代碼中學習如何使用它是很重要的。
javastandardedition(SE)包括javaapi for XML Processing(JAXP),這是一個涵蓋XML處理的大多數方面的總括術語。其中包括:
在本文中,我們使用domapi演示如何從java讀取和寫入XML文件。我們將在以後的文章中介紹另外兩個api。
在本文中,我們使用以下示例XML演示這些概念,可以在這裡找到:
<?xml version="1.0"?><catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applicati*** with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author>...讓我們看看使用domapi讀取XML文件所需的基本步驟。
第一步是獲取DocumentBuilder的實例。生成器用於解析XML文檔。基本用法如下:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setNamespaceAware(false);factory.setValidating(false);DocumentBuilder builder = factory.newDocumentBuilder();我們現在可以從XML根元素開始將整個文檔加載到內存中。在我們的示例中,它是catalog元素。
File file = ...; // XML file to readDocument document = builder.parse(file);Element catalog = document.getDocumentElement();就這樣,夥計們!讀取XML的domapi非常簡單。現在您可以從根元素catalog開始訪問整個XML文檔。現在讓我們看看如何使用它。
既然我們有了XML根元素,就可以使用domapi來提取有趣的信息。
獲取根元素的所有book子元素並在其上循環。注意getChildNodes()返回所有子元素,包括文本、註釋等。出於我們的目的,我們只需要子元素,因此跳過其他元素。
NodeList books = catalog.getChildNodes();for (int i = 0, ii = 0, n = books.getLength() ; i < n ; i++) { Node child = books.item(i); if ( child.getNodeType() != Node.ELEMENT_NODE ) continue; Element book = (Element)child; // work with the book Element here}給定父元素,如何找到特定的子元素?下面的靜態方法返回第一個匹配的元素(如果找到),或者返回null。如您所見,該過程涉及到獲取子節點列表,並在其中循環選擇具有指定名稱的元素節點。
static private Node findFirstNamedElement(Node parent,String tagName){ NodeList children = parent.getChildNodes(); for (int i = 0, in = children.getLength() ; i < in ; i++) { Node child = children.item(i); if ( child.getNodeType() != Node.ELEMENT_NODE ) continue; if ( child.getNodeName().equals(tagName) ) return child; } return null;}注意,domapi將元素中的文本內容視為類型為text\u node的單獨節點。此外,文本內容可能被分割成多個相鄰的文本節點。因此,需要進行以下特殊處理來獲取元素中的文本內容。
static private String getCharacterData(Node parent){ StringBuilder text = new StringBuilder(); if ( parent == null ) return text.toString(); NodeList children = parent.getChildNodes(); for (int k = 0, kn = children.getLength() ; k < kn ; k++) { Node child = children.item(k); if ( child.getNodeType() != Node.TEXT_NODE ) break; text.append(child.getNodeValue()); } return text.toString();}有了這些方便的函數,現在讓我們看一些代碼,從示例XML中列出一些信息。我們想展示每本書的詳細信息,如圖書目錄中提供的信息。
NodeList books = catalog.getChildNodes();for (int i = 0, ii = 0, n = books.getLength() ; i < n ; i++) { Node child = books.item(i); if ( child.getNodeType() != Node.ELEMENT_NODE ) continue; Element book = (Element)child; ii++; String id = book.getAttribute("id"); String author = getCharacterData(findFirstNamedElement(child,"author")); String title = getCharacterData(findFirstNamedElement(child,"title")); String genre = getCharacterData(findFirstNamedElement(child,"genre")); String price = getCharacterData(findFirstNamedElement(child,"price")); String pubdate = getCharacterData(findFirstNamedElement(child,"pubdate")); String descr = getCharacterData(findFirstNamedElement(child,"description")); System.out.printf("%3d. book id = %s" + " author: %s" + " title: %s" + " genre: %s" + " price: %s" + " pubdate: %s" + " descr: %s", ii, id, author, title, genre, price, pubdate, descr);}Java提供了XML轉換API來轉換XML數據。我們使用這個API和身份轉換來生成輸出。
作為一個例子,讓我們向上面的示例目錄添加一個新的book元素。書的細節(如作者、標題等)可以從外部獲得,也許可以從屬性文件或數據庫獲得。我們使用以下屬性文件來加載數據。
id=bk113author=Jane Austentitle=Pride and Prejudicegenre=Romanceprice=6.99publish_date=2010-04-01description="It is a truth universally acknowledged, that a single man in possession of a good fortune must be in want of a wife." So begins Pride and Prejudice, Jane Austen's witty comedy of manners-one of the most popular novels of all time-that features splendidly civilized sparring between the proud Mr. Darcy and the prejudiced Elizabeth Bennet as they play out their spirited courtship in a series of eighteenth-century drawing-room intrigues.第一步是使用上述方法解析現有的XML文件。代碼如下所示。
File file = ...; // XML file to readDocument document = builder.parse(file);Element catalog = document.getDocumentElement();我們使用java提供的properties類從properties文件加載數據。代碼非常簡單,如下所示。
String propsFile = ...;Properties props = new Properties();try (FileReader in = new FileReader(propsFile)) { props.load(in);}加載屬性後,我們將從屬性文件中檢索要添加的值。
String id = props.getProperty("id");String author = props.getProperty("author");String title = props.getProperty("title");String genre = props.getProperty("genre");String price = props.getProperty("price");String publish_date = props.getProperty("publish_date");String descr = props.getProperty("description");現在讓我們創建一個空的book元素。
Element book = document.createElement("book");book.setAttribute("id", id);將子元素添加到書中是很簡單的。為了方便起見,我們在列表中收集所需的元素名稱,並在循環中添加值。
List<String> elnames =Arrays.asList("author", "title", "genre", "price", "publish_date", "description");for (String elname : elnames) { Element el = document.createElement(elname); Text text = document.createTextNode(props.getProperty(elname)); el.appendChild(text); book.appendChild(el);}catalog.appendChild(book);就是這樣做的。catalog元素現在添加了newbook元素。現在剩下的就是寫出更新後的XML。
為了編寫XML,我們需要一個Transformer實例,它的創建如下所示。注意,我們使用setOutputProperty()方法請求輸出XML的縮進。
TransformerFactory tfact = TransformerFactory.newInstance();Transformer tform = tfact.newTransformer();tform.setOutputProperty(OutputKeys.INDENT, "yes");tform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");生成XML輸出的最後一步是應用轉換。結果顯示在輸出流上,系統輸出.
tform.transform(new DOMSource(document), new StreamResult(System.out));要將輸出直接寫入文件,請使用以下命令。
tform.transform(new DOMSource(document), new StreamResult(new File("output.xml")));這就結束了本文關於使用domapi讀寫XML文件的內容。
您在應用程序中使用過domapi嗎?表現如何?請在下面的評論中告訴我們。
...附帶基本功能。 可以使用Adobe Acrobat和Microsoft Word等應用程式編輯PDF。還有免費的線上PDF編輯器,如PDFescape和docub。這些線上編輯可以幫助你以pdf格式填寫表格和求職申請。你將需要上傳檔案,並做一些事情,如**文字,連結,簽...
...是由世界網路聯盟(W3C)開發的。與HTML不同,在XML中,程式設計師可以根據應用程式定義自己的標記,但XML並不是HTML的替代品。XML以純文字格式儲存資料,並且它與平臺無關。XML的主要優點是簡化了資料共享過程。資料可以從...
...建立網頁的結構。XML是更通用的。XML的主要優點是它允許程式設計師自己建立標記。XML是許多Web技術的基礎。其中一些是XHTML、AJAX和Web服務。XHTML是HTML格式的XML語法。AJAX是非同步JavaScript和web服務用來開發API的,一些與XML相關的...
關鍵區別——r與python R是一種高階程式語言,是統計分析和報告的軟體環境。Python是一種高階通用程式語言。因此,R和Python的關鍵區別在於R是一種面向統計的程式語言,而Python是一種通用的程式語言。R可用於統計計算、機...
Web爬網對於自動執行網站上常規執行的某些任務非常有用。你可以像人類一樣編寫一個爬蟲來與網站互動。 ...
... 標記語言是一組程式碼,當應用於純文字時,允許您新增以下一個或多個屬性(以及其他屬性): ...
Python是一種優秀的程式語言。語法可能看起來奇怪和不尋常,但它很容易學習和使用。它支援Minecraft Pi版,以及一系列網站和學術研究專案。 ...
有許多線上工具、瀏覽器擴充套件和桌面外掛可以將網頁轉換為PDF。如果您經常使用這些工具,可能會遇到需要一次性轉換多個連結的情況。一個接一個地做是浪費時間和乏味的。 ...