在Java 中格式化XML 字串
作為Java 開發人員,您可能會遇到這樣的情況:XML 沒有字串換行符或縮進,需要將其轉換為格式良好的字串。這對於調試目的或以可讀方式呈現 XML 資料特別有用。
要完成此任務,您可以利用 Java API for XML 處理 (JAXP) 和文件物件模型 (DOM) 來轉換XML 字串轉換為格式化表示。
首先,從 TransformerFactory 建立一個新的 Transformer 物件。將“INDENT”和“{http://xml.apache.org/xslt}indent-amount”屬性分別設為“yes”和“2”,啟用換行和縮排:
Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
接下來,將XML字串轉換為DOMSource物件:
String inputXml = "<tag><nested>hello</nested></tag>"; DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(inputXml))));
然後,建立一個StreamResult物件來保存格式化的XML string:
StreamResult result = new StreamResult(new StringWriter());
最後,使用轉換器將來源 DOM 轉換為格式化的 XML 字串:
transformer.transform(source, result);
result.getWriter() 物件將包含格式化的XML字串:
String formattedXml = result.getWriter().toString();
範例:
String unformattedXml = ""; Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(unformattedXml)))); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); System.out.println(result.getWriter().toString()); hello
輸出:
<?xml version="1.0" encoding="UTF-8"?> <tag> <nested>hello</nested> </tag>
以上是如何使用 JAXP 和 DOM 在 Java 中格式化未格式化的 XML 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

jdkincludestoolsfordEveloping and compilingjavacode,whilejvmrunsthecompiledbytecode.1)jdkcontainsjre,編譯器,andutilities.2)

Java的關鍵特性包括:1)面向對象設計,2)平台獨立性,3)垃圾回收機制,4)豐富的庫和框架,5)並發支持,6)異常處理,7)持續演進。 Java的這些特性使其成為開發高效、可維護軟件的強大工具。

JavaachievesPlatFormIndependencEthroughByTeCodeAndthejvm.1)sodiscompiledIntobyTecode,notmachinecode.2)thejvminterpretsbytbybytecodeonanyplatform,確保“ writeononce,runany where。”

Java在企業級應用中被廣泛使用是因為其平台獨立性。 1)平台獨立性通過Java虛擬機(JVM)實現,使代碼可在任何支持Java的平台上運行。 2)它簡化了跨平台部署和開發流程,提供了更大的靈活性和擴展性。 3)然而,需注意性能差異和第三方庫兼容性,並採用最佳實踐如使用純Java代碼和跨平台測試。

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)櫥櫃櫥櫃:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載
最受歡迎的的開源編輯器