我使用以下代码创建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();
}
}
但是在标题属性编码中缺失。有什么问题?
答案 0 :(得分: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>