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. Advertising

  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. 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. Replies:
    0
    Views:
    3,373
  2. Gustaf Liljegren
    Replies:
    1
    Views:
    627
    =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=
    Dec 2, 2004
  3. V Green
    Replies:
    0
    Views:
    824
    V Green
    Feb 5, 2008
  4. PA Bear [MS MVP]
    Replies:
    0
    Views:
    929
    PA Bear [MS MVP]
    Feb 5, 2008
  5. MowGreen [MVP]
    Replies:
    5
    Views:
    1,993
    PA Bear [MS MVP]
    Feb 9, 2008
Loading...

Share This Page