gpt4 book ai didi

java - 创建以斜杠 ('' 而不是 '' 结尾的 XML 文档)

转载 作者:行者123 更新时间:2023-12-02 03:34:03 24 4
gpt4 key购买 nike

如果 XML 元素位于一行( <test/> 而不是 <test></test> ),我需要创建以斜杠结尾的 XML 文档

以下是创建 XML 文档的示例代码

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars><supercars company="Ferrari">
<carname type="formula one"></carname>
<carname type="sports"></carname>
</supercars></cars>

但我希望 XML 文档应该是这样的

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars><supercars company="Ferrari">
<carname type="formula one"/>
<carname type="sports"/>
</supercars></cars>

请注意,没有

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class StAXCreateXMLDemo {
public static void main(String[] args) {
try {
StringWriter stringWriter = new StringWriter();

XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(stringWriter);

xMLStreamWriter.writeStartDocument();
xMLStreamWriter.writeStartElement("cars");

xMLStreamWriter.writeStartElement("supercars");
xMLStreamWriter.writeAttribute("company", "Ferrari");

xMLStreamWriter.writeStartElement("carname");
xMLStreamWriter.writeAttribute("type", "formula one");

xMLStreamWriter.writeEndElement();

xMLStreamWriter.writeStartElement("carname");
xMLStreamWriter.writeAttribute("type", "sports");

xMLStreamWriter.writeEndElement();

xMLStreamWriter.writeEndElement();
xMLStreamWriter.writeEndDocument();

xMLStreamWriter.flush();
xMLStreamWriter.close();

String xmlString = stringWriter.getBuffer().toString();

stringWriter.close();

System.out.println(xmlString);

} catch (XMLStreamException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

这可以通过使用 XMLStreamWriter.writeEmptyElement 来完成:

而不是

 xMLStreamWriter.writeStartElement("carname");
xMLStreamWriter.writeAttribute("type", "formula one");
xMLStreamWriter.writeEndElement();

使用

xMLStreamWriter.writeEmptyElement("carname");
xMLStreamWriter.writeAttribute("type", "formula one");

关于java - 创建以斜杠 ('<test/>' 而不是 '<test></test>' 结尾的 XML 文档),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com