web-dev-qa-db-fra.com

Jolie impression de sortie de javax.xml.transform.Transformer avec uniquement une API Java standard (positionnement par indentation et Doctype)

En utilisant le code simple suivant:

package test;

import Java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class TestOutputKeys {
    public static void main(String[] args) throws TransformerException {

        // Instantiate transformer input
        Source xmlInput = new StreamSource(new StringReader(
                "<!-- Document comment --><aaa><bbb/><ccc/></aaa>"));
        StreamResult xmlOutput = new StreamResult(new StringWriter());

        // Configure transformer
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(); // An identity transformer
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);

        System.out.println(xmlOutput.getWriter().toString());
    }

}

Je reçois la sortie:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Document comment --><!DOCTYPE aaa SYSTEM "testing.dtd">

<aaa>
<bbb/>
<ccc/>
</aaa>

Question A: La balise doctype apparaît après le commentaire du document. Est-il possible de le faire apparaître avant le commentaire du document?

Question B: Comment obtenir une indentation en utilisant uniquement l’API JavaSE 5.0? Cette question est essentiellement identique à Comment imprimer joliment du xml à partir de Java , cependant presque toutes les réponses à cette question dépendent sur des bibliothèques externes. La seule réponse applicable (publiée par un utilisateur nommé Lorenzo Boccaccia) qui utilise uniquement l’API de Java est fondamentalement égale au code affiché ci-dessus, mais ne fonctionne pas pour moi (comme indiqué dans le résultat, je n’obtiens pas d’indentation).

Je suppose que vous devez définir le nombre d'espaces à utiliser pour l'indentation, comme le font de nombreuses réponses avec des bibliothèques externes, mais je ne trouve pas où spécifier cela dans l'API Java. Compte tenu du fait que la possibilité de définir une propriété d'indentation sur "oui" existe dans l'api Java, il doit être possible d'effectuer l'indentation d'une manière ou d'une autre. Je n'arrive pas à comprendre comment.

55
Alderath

La partie manquante est le montant à mettre en retrait. Vous pouvez définir le retrait et le montant du retrait comme suit:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.Apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
112
Rich Seller

Une petite classe utilitaire à titre d'exemple ...

import org.Apache.xml.serialize.XMLSerializer;

public class XmlUtil {

public static Document file2Document(File file) throws Exception {
    if (file == null || !file.exists()) {
        throw new IllegalArgumentException("File must exist![" + file == null ? "NULL"
                : ("Could not be found: " + file.getAbsolutePath()) + "]");
    }
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    return dbFactory.newDocumentBuilder().parse(new FileInputStream(file));
}

public static Document string2Document(String xml) throws Exception {
    InputSource src = new InputSource(new StringReader(xml));
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    return dbFactory.newDocumentBuilder().parse(src);
}

public static OutputFormat getPrettyPrintFormat() {
    OutputFormat format = new OutputFormat();
    format.setLineWidth(120);
    format.setIndenting(true);
    format.setIndent(2);
    format.setEncoding("UTF-8");
    return format;
}

public static String document2String(Document doc, OutputFormat format) throws Exception {
    StringWriter stringOut = new StringWriter();
    XMLSerializer serial = new XMLSerializer(stringOut, format);
    serial.serialize(doc);
    return stringOut.toString();
}

public static String document2String(Document doc) throws Exception {
    return XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}

public static void document2File(Document doc, File file) throws Exception {
    XmlUtil.document2String(doc, XmlUtil.getPrettyPrintFormat());
}

public static void document2File(Document doc, File file, OutputFormat format) throws Exception {
    XMLSerializer serializer = new XMLSerializer(new FileOutputStream(file), format);
    serializer.serialize(doc);
}
}

XMLserializer est fourni par xercesImpl à partir de Apache Foundation . Voici la dépendance maven:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>

Vous pouvez trouver la dépendance de votre outil de construction préféré ici: http://mvnrepository.com/artifact/xerces/xercesImpl/2.11.0 .

4
Rob

Vous pourriez probablement tout gâcher avec un fichier XSLT . Google donne quelques résultats, mais je ne peux pas me prononcer sur leur exactitude.

1
McDowell

Pour que la sortie soit un document XML valide, NO. Un document XML valide doit commencer par une instruction de traitement. Voir la spécification XML http://www.w3.org/TR/REC-xml/#sec-prolog-dtd pour plus de détails.

0
Oskar