1

I create xml using code like this:

    public static void main(String[] args) {
        XMLOutputFactory factory      = XMLOutputFactory.newInstance();
        XMLEventFactory  eventFactory = XMLEventFactory.newInstance();
        try {
            XMLEventWriter writer =
                    factory.createXMLEventWriter(System.out);

            XMLEvent event = eventFactory.createStartDocument("utf-8");
            writer.add(event);

            event = eventFactory.createStartElement(
                    "", "", "test");
            writer.add(event);
            event = eventFactory.createEndElement(
                    "", "", "test");
            writer.add(event);
            writer.flush();
            writer.close();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
    }

But in header attribute encoding is missing. What is wrong?

1 Answer 1

1

The encoding is missing only for "utf-8". If you specify a different encoding, the encoding is included in the XML declaration. UTF-8 is the default encoding for XML so this is not really an error.

But if you are not using System.out the encoding is included even for "UTF-8". Here for example with a StringWriter:

public static void main(String[] args) {
  XMLOutputFactory factory      = XMLOutputFactory.newInstance();
  XMLEventFactory  eventFactory = XMLEventFactory.newInstance();
  try {

    StringWriter sw = new StringWriter();

    XMLEventWriter writer =
        factory.createXMLEventWriter(sw);

    XMLEvent event = eventFactory.createStartDocument("utf-8");
    writer.add(event);

    event = eventFactory.createStartElement(
        "", "", "test");
    writer.add(event);
    event = eventFactory.createEndElement(
        "", "", "test");
    writer.add(event);
    writer.flush();
    writer.close();

    sw.close();
    System.out.println(sw.toString());

  } catch (XMLStreamException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Then the result is: <?xml version="1.0" encoding="utf-8"?><test></test>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.