How to perform XML style checking?

257 Views Asked by At

Unformatted XML is a problem in our build. I would like to include style checking for XML documents, primarily looking for poor indentation.

What is the best tool to use? (The build uses Ant).

2

There are 2 best solutions below

0
On

Check XCOP: http://www.yegor256.com/2017/08/29/xcop.html

This is how you integrate it with ant:

<project>
  <target name="xcop">
    <apply executable="xcop" failonerror="true">
      <fileset dir=".">
        <include name="**/*.xml"/>
        <include name="**/*.xsd"/>
        <exclude name="target/**/*"/>
        <exclude name=".idea/**/*"/>
      </fileset>
    </apply>
  </target>
</project>
1
On

You can write a class that will automatically transform and therefore indent your XML. Then just specify in Ant on which XML files it should be ran.

Something to get you started:

String filePath = "test.xml";
String outputFilePath = "testOut.xml";

File xmlFile = new File(filePath);
File outputXmlFile = new File(outputFilePath);

Transformer transformer = TransformerFactory.newInstance().newTransformer();

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

StreamSource ss = new StreamSource(xmlFile);
StreamResult sr = new StreamResult(outputXmlFile);      

transformer.transform(ss, sr);