1

我使用这样的代码创建 xml:

    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();
        }
    }

但是在标头属性编码中丢失了。怎么了?

4

1 回答 1

1

仅“utf-8”缺少编码。如果您指定不同的编码,则该编码包含在 XML 声明中。UTF-8 是 XML 的默认编码,因此这并不是真正的错误。

但是,如果您不使用System.out编码,即使是“UTF-8”也包括在内。例如,这里有一个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();
  }
}

那么结果是:<?xml version="1.0" encoding="utf-8"?><test></test>

于 2013-10-16T13:56:02.850 回答