any easy way to write out a XML DOM object to file?

Discussion in 'Java' started by Kaidi, Nov 25, 2004.

  1. Kaidi

    Kaidi Guest

    Hello!

    I am using Document and DOM to hold a XML file, and make some changes
    to the Document. After that, I just wonder is there any easy way to
    write the modified XML file back to disk? (loop all the nodes and
    print them out is one way of course, any other better way?)

    The piece of node is:

    String filename="mytest.xml";
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new
    File(filename));
    // changes the doc, add, edit nodes, etc.

    Now, I want to get the updated xml file from "doc", what to do?
    Anything like doc.writeAsXMLFile("newFile.xml")?

    Thanks and happy holiday. :)
    Kaidi, Nov 25, 2004
    #1
    1. Advertising

  2. Kaidi

    Alex Kizub Guest

    >
    > Now, I want to get the updated xml file from "doc", what to do?
    > Anything like doc.writeAsXMLFile("newFile.xml")?
    >


    OutputFormat format = new OutputFormat(doc);
    Writer writer = new FileWriter("newFile.xml");
    XMLSerializer ser = new XMLSerializer(writer, format);
    ser.serialize(doc);
    writer.close();

    Alex Kizub.
    Alex Kizub, Nov 25, 2004
    #2
    1. Advertising

  3. Hello,

    XMLSerializer is deprecated (old xerces).
    Some code I use to transform a Document into a String:

    Document document = ...;
    DOMSource domSource = new DOMSource(document);
    StreamResult streamResult = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
    // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
    serializer.transform(domSource, streamResult);
    String result = writer.getBuffer().toString();

    Best regards,
    feri
    Ferenc Hechler, Nov 26, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nonee
    Replies:
    3
    Views:
    919
    Manchild
    Sep 2, 2005
  2. Replies:
    0
    Views:
    535
  3. Jim Mitten
    Replies:
    3
    Views:
    411
    Joseph Kesselman
    Jan 29, 2008
  4. Mike Barnard
    Replies:
    5
    Views:
    3,467
    Toby A Inkster
    Mar 27, 2008
  5. Joshua Muheim
    Replies:
    2
    Views:
    120
    Aaron Patterson
    Oct 13, 2009
Loading...

Share This Page