通过C#遍历XML文件

时间:2018-10-03 18:47:53

标签: c# xml

我有这种类型的XML文件,用于存储配置值:

<assets>
  <asset enabled="false" name="ListTypes" internalName="List" duplicateCheckField="" enableCustomFields="true"></asset>
  <asset enabled="false" name="Members" internalName="Member" duplicateCheckField="Username" enableCustomFields="false"></asset>
</assets>

我想遍历每个资产并获取每个元素的值,并将其存储在资产列表中。

我有以下代码:

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            processConfiguration();
        }

        public static void processConfiguration()
        {
            XDocument assets = XDocument.Load("assets.xml");
            List<asset> assetList = new List<asset>();

            // this line is not working out for me as I cannot get each attr value
            // by attr I mean enabled, name, etc for each row
            foreach (var row in assets.Descendants("asset").ToList())
            {
                asset a = new asset();
                // once i have the foreach correct I can build my list.
            }

        }

        public class asset
        {
            public bool enabled { get; set; }
            public string name { get; set; }
            public string internalName { get; set; }
            public string duplicateCheckField { get; set; }
            public bool enableCustomFields { get; set; }

        }

    }
}

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

您可以使用XElement.Attribute访问属性值。您还可以使用LINQ to XML来缩短代码:

XDocument assets = XDocument.Load("assets.xml");
var assetList = assets.Descendants("asset")
                      .Select(row => new asset {
                           enabled = (bool)row.Attribute("enabled"),
                           name = row.Attribute("name").Value,
                           internalName = row.Attribute("internalName").Value,
                           duplicateCheckField = row.Attribute("duplicateCheckField").Value,
                           enableCustomFields = (bool)row.Attribute("enabledCustomFields")
                       }).ToList();