简体   繁体   English

如何生成格式化的.xml文件?

[英]how to generate formatted .xml file?

I'm writing a program that produces an xml file. 我正在编写一个生成xml文件的程序。 The code works perfectly giving the expected result.But it gives me only a single line document. 该代码可以完美地提供预期的结果,但是它只给我一个单行文档。 I want it to be in formatted way and correctly indented.Is there a way to do that? 我希望它采用格式化的方式并正确缩进,有没有办法做到这一点? Here is the code i used 这是我使用的代码

public class Main {

    public static void main(String[] args) {
        WriteXml(7, 9, 0);
    }

    public static void WriteXml(int WS1, int FTP1, int EMAIL1) {

        try {
            final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
            final Document document = documentBuilder.newDocument();
            final Element root = document.createElement("Counter");
            document.appendChild(root);
            final Element properties = document.createElement("properties");
            root.appendChild(properties);

            final Element webservice = document.createElement("age");
            webservice.appendChild(document.createTextNode(Integer.toString(WS1)));
            properties.appendChild(webservice);

            final Element ftp = document.createElement("id");
            ftp.appendChild(document.createTextNode(Integer.toString(FTP1)));
            properties.appendChild(ftp);

            final Element email = document.createElement("grade");
            email.appendChild(document.createTextNode(Integer.toString(EMAIL1)));
            properties.appendChild(email);

            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            final DOMSource domSource = new DOMSource(document);
            final StreamResult streamResult = new StreamResult(new File("src/counter.xml"));
            transformer.transform(domSource, streamResult);

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

and this gives me the following xml document 这给了我下面的xml文档

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Counter><properties><age>7</age><id>9</id><grade>0</grade></properties></Counter>

But i want it to be more like this 但我希望它更像这样

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Counter>
    <properties>
        <age>7</age>
        <id>9</id>
        <grade>0</grade>
    </properties>
</Counter>

您可以在变压器的输出上设置几个属性,其中一个用于缩进:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

With some guessing and after looking at this question adding these lines after obtaining the transformer might do the trick 经过一些猜测,在看了这个问题之后,在获得变压器后添加了这些线可能会解决问题

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

Underscore-java library has static method U.formatXml(xmlstring). Underscore -java库具有静态方法U.formatXml(xmlstring)。 I am the maintainer of the project. 我是该项目的维护者。 Live example 现场例子

import com.github.underscore.lodash.U;

String formattedXml = U.formatXml(xmlstring); 

I created the following method: 我创建了以下方法:

public String prettyPrintXml(String xmlStringToBeFormatted) {
    String formattedXmlString = null;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource(new StringReader(xmlStringToBeFormatted));
        Document document = documentBuilder.parse(inputSource);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StreamResult streamResult = new StreamResult(new StringWriter());
        DOMSource dOMSource = new DOMSource(document);
        transformer.transform(dOMSource, streamResult);
        formattedXmlString = streamResult.getWriter().toString().trim();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    return formattedXmlString;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM