c# - 如何在 XML 中创建数组
问题描述
我需要帮助在里面创建数组XML document
。
我可以使用单个用户创建一个文件,但这需要是一个列表。
我有这个UserList.cs
[XmlRoot("MyList")]
public class MyListXml
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Date")]
public string Date { get; set; }
[XmlElement("User")]
public UserXml usersXml { get; set; }
public class UserXml
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
}
这在我的控制器里面
public void GetUsersXml()
{
MyListXml myListXml = new MyListXml
{
Id = 5,
Date = DateTime.Today.ToString("yyyy-MM-dd"),
UsersXml = new UserXml
{
Id = 111,
Name = "John Doe",
}
};
userListXml.SaveXml("userList.xml");
}
我正在获取包含以下数据的 XML 文档
<?xml version="1.0"?>
<MyList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>5</Id>
<Date>2019-11-04</Date>
<User>
<Id>111</Id>
<Name>John Doe</Name>
</User>
</MyList>
但就像我说的,我需要一个list of users
,像这样
<?xml version="1.0"?>
<MyList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>5</Id>
<Date>2019-11-04</Date>
<User>
<Id>111</Id>
<Name>John Doe</Name>
</User>
<User>
<Id>112</Id>
<Name>Jane Doe</Name>
</User>
<User>
<Id>113</Id>
<Name>Bill Doe</Name>
</User>
</MyList>
我知道我需要使用foreach
来自我的数据database
,但我不确定在哪里放置 aforeach
也不知道我的代码是否正确......
解决方案
使用以下:
[XmlRoot("MyList")]
public class MyListXml
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Date")]
public string Date { get; set; }
[XmlElement("User")]
public List<UserXml> usersXml { get; set; }
}
public class UserXml
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
推荐阅读
- linux - 错误:无法解析 conf/bitbake.conf:[Errno 2]
- entity-framework-core - 在 EF Core 5 中重命名多对多关系中的字段
- eclipse-plugin - 是否可以在 frangment.e4xmi 中安排handledmenuitem 的排序/顺序
- android - BottomSheetDialog 内 VideoView 的 MediaController 隐藏在 BottomSheetDialog 后面
- vue.js - 如何专注于 vuejs 中的 v-for 中的输入
- python - 在 tkinter 树视图中合并节点
- python - 如何为 sklearn 多类 ROC-AUC 分数使用不同的标签顺序?
- php - 诗篇检查“死亡”的呼唤
- reactjs - 根据使用的语言更改密钥
- json - 转换json对象时找不到类型转换器?