Java 中的XML 美化
問題:
問題:如何增強可讀性和格式以字串形式儲存的XML Java?
簡介:XML(可擴展標記語言)通常缺乏適當的縮排和換行符,使其難以閱讀和解釋。格式化 XML 可以提高其可讀性,並使其更易於導航和理解。
程式碼解決方案:import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class XmlBeautifier { public static String formatXml(String unformattedXml) { try { // Create a transformer to modify the XML Transformer transformer = TransformerFactory.newInstance().newTransformer(); // Set indenting and indentation amount transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Convert the XML string to a DOM source DOMSource source = new DOMSource(new DocumentBuilder().parse(new InputSource(new StringReader(unformattedXml)))); // Format the XML and store the result in a string StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); } catch (TransformerException | ParserConfigurationException | SAXException e) { // Handle any exceptions throw new RuntimeException(e); } } }
String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = XmlBeautifier.formatXml(unformattedXml);
用法範例:
<?xml version="1.0" encoding="UTF-8"?> <root> <tag> <nested>hello</nested> </tag> </root>
輸出範例:
以上是如何在 Java 中美化 XML 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!