Embellissement XML en Java
Question :
Comment pouvons-nous améliorer la lisibilité et le formatage de XML stocké sous forme de chaîne dans Java ?
Introduction :
XML (Extensible Markup Language) manque souvent d'indentation et de sauts de ligne appropriés, ce qui le rend difficile à lire et à interpréter. Le formatage XML améliore sa lisibilité et facilite la navigation et la compréhension.
Solution de code :
En utilisant l'API Java, nous pouvons formater une chaîne XML pour la rendre plus lisible :
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); } } }
Exemple d'utilisation :
String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = XmlBeautifier.formatXml(unformattedXml);
Sortie Exemple :
<?xml version="1.0" encoding="UTF-8"?> <root> <tag> <nested>hello</nested> </tag> </root>
Remarques :
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!