Java의 XML 미화
질문:
가독성과 서식을 어떻게 향상시킬 수 있나요? 문자열로 저장된 XML Java?
소개:
XML(Extensible Markup Language)에는 적절한 들여쓰기와 줄 바꿈이 부족하여 읽고 해석하기 어려운 경우가 많습니다. XML 형식을 지정하면 가독성이 향상되고 탐색 및 이해가 더 쉬워집니다.
코드 솔루션:
Java API를 활용하면 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!