javaxmlxml-serializationxom

how to write XOM document to XML file with pretty print?


I used the following code to write the xml

    import nu.xom.Document;
    import nu.xom.Element;
    import nu.xom.Serializer;

    Element root = new Element("ADT");
    root.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema");
    root.setNamespaceURI("urn:hl7-org:v3");

    Element msh = new Element("MSH", "urn:hl7-org:v3");
    Element msh_1 = new Element("MSH.1", "urn:hl7-org:v3");
    msh_1.appendChild(m.getFieldSeperator());
    Element msh_2 = new Element("MSH.2", "urn:hl7-org:v3");
    msh_2.appendChild(m.getEncodingCharacters());

    msh.appendChild(msh_1);
    msh.appendChild(msh_2);

    root.appendChild(msh);
    Document document = new Document(root);
    Serializer serializer;
    serializer = new Serializer(System.out, "UTF-8");
    serializer.setIndent(4);
    serializer.write(document);

That prints my xml document on the console with pretty print. If anyone can help me to get the same same to an xml file? Thank you


Solution

  • FileOutputStream fileOutputStream = new FileOutputStream ("out.xml")
    serializer = new Serializer(fileOutputStream, "UTF-8");
    serializer.setIndent(4);
    serializer.write(document);
    //close fileOutputStream  ...