How do I add the XML Version and Encoding Declaration to XML?

Discussion in 'Java' started by eric.jester@gmail.com, Apr 21, 2005.

  1. Guest

    Hello,

    I a org.w3c.dom.Document that does not have the <?xml version="1"
    encoding="UTF-8"?> declaration on it. Is there a way I can add this to
    it?

    Thanks,

    Eric
     
    , Apr 21, 2005
    #1
    1. Advertisements

  2. Michael Berg Guest

    Hi,

    > I a org.w3c.dom.Document that does not have the <?xml version="1"
    > encoding="UTF-8"?> declaration on it. Is there a way I can add this to
    > it?


    What are you using to serialize the Document to XML? In my experience using
    the Transformer class from Xerces outputs an XML document that is
    appropriately formatted:

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    // I have to read this stuff manually from time to time so make it pretty
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");

    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4
    ");
    transformer.transform(new DOMSource(xml),result); // xml is your Document
    instance
    ...
    xmlstring = result.toString();

    'Result' having been previously created as a StreamResult object - for
    example like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(
    new java.io_OutputStreamWriter(
    baos,
    "UTF-8"
    )
    );

    But of course there are many other ways to do this. Your mileage may vary.

    /Michael
    www.hyperpal.com
    www.bergconsult.com
     
    Michael Berg, Apr 22, 2005
    #2
    1. Advertisements

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. Hardy Wang

    Encoding.Default and Encoding.UTF8

    Hardy Wang, Jun 8, 2004, in forum: ASP .Net
    Replies:
    5
    Views:
    19,822
    Jon Skeet [C# MVP]
    Jun 9, 2004
  2. eitan
    Replies:
    0
    Views:
    454
    eitan
    Dec 9, 2003
  3. Replies:
    0
    Views:
    3,748
  4. mel-tey chamon!
    Replies:
    2
    Views:
    1,544
    Patrick TJ McPhee
    May 16, 2004
  5. kelvSYC
    Replies:
    6
    Views:
    8,029
    Richard Herring
    May 17, 2005
  6. Gustaf Liljegren
    Replies:
    1
    Views:
    902
    =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=
    Dec 2, 2004
  7. Sylvain Thenault
    Replies:
    2
    Views:
    619
    Sylvain Thenault
    Jan 18, 2005
  8. MowGreen [MVP]
    Replies:
    5
    Views:
    2,377
    PA Bear [MS MVP]
    Feb 9, 2008
Loading...