Вопрос

My code happens to be like this:

<project>
           <target>
        <for list = ... >
        <if>
                <not>
                </not>
                <then>
                    <fail>
                         </fail>
                </then>
        </if>
        </for>
    </target>
</project>

I want it to format it to make it look like this:

<project>
    <target>
        <for list = ... >
            <if>
                <not>
                </not>
                <then>
                    <fail>
                    </fail>
                </then>
            </if>
        </for>
    </target>
</project>

I thought about going with regex but is there any other ways that I can do this?

Это было полезно?

Решение

You can use the Transformer class included in the JDK and do something like this:

import javax.xml.transform.OutputKeys;
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;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

String xml = "<your XML goes here>..."

File file = new File("output.xml");

try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) {
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
}

Другие советы

XML is not a regular language, regexes don't work for generic XML documents.

Use any XML parser / writer that allows you to set the output formatting, e.g. JSoup or even the standard library capabilities.

Most IDE's (Eclipse, NetBeans) will do that for you.

Also, online tools can also do it in a nap. For instance:

http://www.shell-tools.net/index.php?op=xml_format

http://www.corefiling.com/opensource/xmlpp.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top