首页 > 解决方案 > 如何在 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也不知道我的代码是否正确......

标签: c#xmlasp.net-core

解决方案


使用以下:

    [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; }

    }

推荐阅读