在 Java 中將 XML 解析為字串
1. 概述
有時,我們可能會遇到需要將 XML(可擴展標記語言)字串轉換為我們可以處理的實際 XML 文件的場景。它在網路爬行或檢索資料庫中儲存的 XML 資料等任務中更為常見。
在本文中,我們將討論如何將 XML 字串轉換為 XML 文件。我們將介紹解決該問題的兩種方法。
2. 範例字串
我們將使用一個簡單的 XML 文檔,其中包含有關部落格文章的資料:
<posts>
<post postId="1">
<title>Parsing XML as a String in Java</title>
<author>John Doe</author>
</post>
</posts>
posts是包含post作為子項的根。
3. 從字串中解析 XML
在本節中,我們將介紹從範例字串中解析 XML 的兩種方法。
3.1.帶有StringReader的InputSource
當我們解析 XML 文件時,我們會建立一個DocumentBuilder類別的實例。然後,我們呼叫實例上的parse方法,該方法需要一個輸入來源來解析 XML。
在我們的例子中,XML 是一個字串。因此,如果我們直接將字串傳遞給parse方法,就會拋出異常。這是因為 parse 方法期望字串是指向 XML 資源的 URI(統一資源識別碼)。
幸運的是,我們可以為 XML 字串建立自訂輸入來源。我們可以使用StringReader類別從 XML 字串建立字元流。然後,我們從該流中建立一個新的輸入來源:
String xmlString = "<posts>...</posts>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xmlString));
Document document = builder.parse(inputSource);
讓我們來分解一下:
-
xmlString是我們的範例 XML 字串 -
DocumentBuilder是一個幫助器類,可讓我們解析和建立 XML 文檔 -
InputSource是一個包裝器,可以使用來自各種來源(例如文件、字串和流)的 XML 數據 -
StringReader將 XML 字串轉換為可讀取的字元流
本質上, InputSource可以採用Reader物件將其解析為 XML:
public InputSource(Reader characterStream)
類似地, parse方法採用一個InputSource :
public Document parse(InputSource is)
最終, parse方法根據字串建立 XML 文件。我們可以透過將範例文件作為字串傳遞給它來測試它:
@Test
public void givenXmlString_whenConvertToDocument_thenSuccess() {
...
assertNotNull(document);
assertEquals("posts", document.getDocumentElement().getNodeName());
Element rootElement = document.getDocumentElement();
var childElements = rootElement.getElementsByTagName("post");
assertNotNull(childElements);
assertEquals(1, childElements.getLength());
}
如果 XML 字串是有效的標記,我們可以預期測試會通過。
3.2.位元組數組的InputStream
使用InputStream是解析 XML 的另一種常見方法。當我們需要從網路流或檔案流等流解析 XML 時,它就非常有用。此外,它比InputSource使用起來更簡單,這讓我們可以微調解析過程。
首先,我們從 XML 字串建立ByteArrayInputStream的實例。然後,我們將其提供給parse方法:
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
Document document = builder.parse(inputStream);
在程式碼中,我們將字串轉換為位元組數組。另外,我們也指定了字元編碼,本例為UTF-8。
4. 結論
In this article, we reviewed the two most common approaches to converting an XML string to an XML document in Java. Specifically, we converted an XML string to a character stream and parsed it as an input source. Similarly, we covered how to parse the string as an input byte array stream.
與往常一樣,這些範例的所有程式碼都可用 在 GitHub 上。