gpt4 book ai didi

java - 在 .xml 文件顶部写入注释?

转载 作者:行者123 更新时间:2023-12-01 17:44:47 25 4
gpt4 key购买 nike

我目前正在编写一个写入 .xml 文件的程序。我想在文件顶部(第一行)放置一条注释,说明更改代码将如何搞乱它。使用 XMLEncoder 可以实现这一点吗?

这是我的代码:

private static void serializeToXML(ArrayList<Item> list)
{
try
{
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream(getSaveLocation())));
encoder.writeObject(list);
encoder.close();

} catch (FileNotFoundException e)
{
System.err.println("Error writing list to XML File.");
}
}

谢谢!

最佳答案

首先,在<?xml ... ?>之前不能有任何东西。 .

我想以下 xml 应该是您可能想要的:

<?xml version='1.0' encoding='UTF-8'?>
<!--Some insightful commentary here-->
<SomePojo>
<id>1</id>
<name>pojo1</name>
</SomePojo>

您可以尝试 jackson-dataformat-xml。

测试代码

import java.io.StringWriter;

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

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import org.testng.annotations.Test;

public class XMLWriteCommentTest {

@Test
public void test() throws Exception {
// First create Stax components we need
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
StringWriter out = new StringWriter();
XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(out);

// then Jackson components
XmlMapper mapper = new XmlMapper(xmlInputFactory);

sw.writeStartDocument();
// comment
sw.writeComment("Some insightful commentary here");
// Write whatever content POJOs...
mapper.writeValue(sw, new SomePojo("1", "pojo1"));

sw.writeEndDocument();
// getResult
String xml = out.toString();
System.out.println(xml);
}
}
class SomePojo {
private String id;
private String name;

public SomePojo(String id, String name){
this.id = id;
this.name = name;
}

public String getId(){
return this.id;
}

public void setId(String id){
this.id = id;
}

public String getName(){
return this.name;
}

public void setName(String name){
this.name = name;
}
}

Maven 依赖

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.1</version>
</dependency>

关于java - 在 .xml 文件顶部写入注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60881042/

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