我正在尝试使用C#中的XDocument创建XML文件。
该文件具有以下结构:
< acc Account="test" Partner="2144" CITY="Munsbach" />
< acc Account="test" Partner="2144" CITY="(Schuttrange" />
< acc Account="test" Partner="2145" CITY="Rumelange" />
< acc Account="test" Partner="2145" CITY="Belvaux" />
< acc Account="test" Partner="2145" CITY="Sassel" />
我手动添加了换行符以便更好地阅读。
有人可以帮我吗?
谢谢, Jeppen
答案 0 :(得分:1)
我更喜欢编写这样的数据类:
[Serializable]
[XmlRoot("acc")]
public class Account
{
[XmlElement("Account")]
public string Account { get; set; }
[XmlElement("Partner")]
public int Partner { get; set; }
[XmlElement("CITY")]
public string City { get; set; }
}
并使用XmlSerializer
序列化/反序列化它。
List<AccountClass> accounts = new List<AccountClass>
{
new AccountClass { Account = "test", Partner = 2144, City = "Munsbach" },
new AccountClass { Account = "test", Partner = 2144, City = "Schuttrange" }
};
XmlSerializer ser = new XmlSerializer(typeof(List<AccountClass>));
using (FileStream fileStream = new FileStream("File.xml", FileMode.OpenOrCreate))
{
ser.Serialize(fileStream, accounts);
}
您的文件将如下所示:
<?xml version="1.0"?>
<ArrayOfAccountClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AccountClass>
<Account>test</Account>
<Partner>2144</Partner>
<CITY>Munsbach</CITY>
</AccountClass>
<AccountClass>
<Account>test</Account>
<Partner>2144</Partner>
<CITY>Schuttrange</CITY>
</AccountClass>
</ArrayOfAccountClass>