C# 在C中编写迭代时跳过XML头#
我对C#很陌生,所以如果这个问题很容易回答,我会提前道歉。。。 我有一个程序,可以创建一些对象并将它们的属性写入文本文件(.txt)。 从这个文本文件中,它每隔一行读取一个ID,并用这些ID创建一组新对象 我应该获取这些新对象,将它们添加到C# 在C中编写迭代时跳过XML头#,c#,xml,serialization,C#,Xml,Serialization,我对C#很陌生,所以如果这个问题很容易回答,我会提前道歉。。。 我有一个程序,可以创建一些对象并将它们的属性写入文本文件(.txt)。 从这个文本文件中,它每隔一行读取一个ID,并用这些ID创建一组新对象 我应该获取这些新对象,将它们添加到列表,然后将它们写入XML文件。现在,考虑到我已经放弃尝试将这些对象(以及它们各自的属性)添加到列表中,因为我无法使其工作,我正在尝试获取这些对象并将其写入XML 这是相关的代码位: for (int i = 0; i <= 200; i += 2)
列表
,然后将它们写入XML文件。现在,考虑到我已经放弃尝试将这些对象(以及它们各自的属性)添加到列表中,因为我无法使其工作,我正在尝试获取这些对象并将其写入XML
这是相关的代码位:
for (int i = 0; i <= 200; i += 2)
{
//Functions of IAnimal take int values so the string needs to be converted.
int nooID = Convert.ToInt32(animalist[i]);
//Create a new animal for every iteration and assign it the new ID/name.
IAnimal nooanimal = new IAnimal();
nooanimal.setID(nooID);
nooanimal.setname(nooID);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(nooanimal.GetType());
using (StreamWriter streamWriter = System.IO.File.AppendText("animalist.xml"))
{
serializer.Serialize(streamWriter, nooanimal);
}
}
for(int i=0;i
创建自定义XmlWriterSettings
将属性设置为true
使用这些设置创建一个XmlWriter
,并序列化到其中
有效的XML文件应仅包含一个根元素。但是,如果删除重复的头
,XML文件仍将无效。
试试这个:
List<IAnimal> animals = new List<IAnimal>();
for (int i = 0; i <= 200; i += 2)
{
//Functions of IAnimal take int values so the string needs to be converted.
int nooID = Convert.ToInt32(animalist[i]);
//Create a new animal for every iteration and assign it the new ID/name.
IAnimal nooanimal = new IAnimal();
nooanimal.setID(nooID);
nooanimal.setname(nooID);
animals.Add(nooanimal);
}
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(List<IAnimal>));
using (StreamWriter streamWriter = System.IO.File.AppendText("animalist.xml"))
{
serializer.Serialize(streamWriter, animals);
}
列出动物=新建列表();
对于(int i=0;i使用属性控制序列化可能很有用:这解决了我的两个问题!谢谢!我不明白为什么当我尝试将每个nooamal
添加到List
(获取列表的计数总是返回1)…时它不起作用,但我现在可以调查:)这段代码之所以不重复标题,是因为它写入了列表,而不是与对象一起进行每次迭代吗?@Nicholas这段代码之所以不重复标题,是因为它写入了列表,而不是与对象一起进行每次迭代吗?
是的。当您将一些数据序列化为XML时,将始终是一个最上面的元素,它将保存在所有数据中。在您的情况下,该对象是List
。
List<IAnimal> animals = new List<IAnimal>();
for (int i = 0; i <= 200; i += 2)
{
//Functions of IAnimal take int values so the string needs to be converted.
int nooID = Convert.ToInt32(animalist[i]);
//Create a new animal for every iteration and assign it the new ID/name.
IAnimal nooanimal = new IAnimal();
nooanimal.setID(nooID);
nooanimal.setname(nooID);
animals.Add(nooanimal);
}
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(List<IAnimal>));
using (StreamWriter streamWriter = System.IO.File.AppendText("animalist.xml"))
{
serializer.Serialize(streamWriter, animals);
}