简体   繁体   中英

parse xml children nodes

What is the best way to parse XML children nodes into a specific list? This is a small example of the XML.

<Area Name="Grey Bathroom" IntegrationID="3" OccupancyGroupAssignedToID="141">
  <Outputs>
  <Output Name="Light/Exhaust Fan" IntegrationID="46" OutputType="NON_DIM" Wattage="0" /> 
  </Outputs>
</Area>

I want to create a list or something that will be called the Area Name and hold the information of the Output Name and IntegrationID. So I can call the list and pull out the Output Name and IntegrationID.

I can create a list of all Area Names and then a list of Outputs but cannot figure out how to create a list that will be called "Grey Bathroom" and hold the output "Light/Exhaust Fan" with an ID of 46.

XDocument doc = XDocument.Load(@"E:\a\b.xml");
        List<Area> result = new List<Area>();
        foreach (var item in doc.Elements("Area"))
        {
            var tmp = new Area();
            tmp.Name = item.Attribute("Name").Value;
            tmp.IntegrationID = int.Parse(item.Attribute("IntegrationID").Value);
            tmp.OccupancyGroupAssignedToID = int.Parse(item.Attribute("OccupancyGroupAssignedToID").Value);

            foreach (var bitem in item.Elements("Outputs"))
            {
                foreach (var citem in bitem.Elements("Output"))
                {
                    tmp.Outputs.Add(new Output
                    {
                        IntegrationID = int.Parse(citem.Attribute("IntegrationID").Value),
                        Name = citem.Attribute("Name").Value,
                        OutputType = citem.Attribute("OutputType").Value,
                        Wattage = int.Parse(citem.Attribute("Wattage").Value)
                    });
                }
            }
            result.Add(tmp);
        }

public class Area
{
    public String Name { get; set; }
    public int IntegrationID { get; set; }
    public int OccupancyGroupAssignedToID { get; set; }
    public List<Output> Outputs = new List<Output>();
}

public class Output
{
    public String Name { get; set; }
    public int IntegrationID { get; set; }
    public String OutputType { get; set; }
    public int Wattage { get; set; }
}

The example uses an anonymous type. You could (and I warmly advice you to) use your own.

var doc = XDocument.Parse(xml);
var areaLists = doc.Elements("Area").
                    Select(e => e.Descendants("Output").
                        Select(d => new
                        {
                            Name = (string) d.Attribute("Name"),
                            Id = (int) d.Attribute("IntegrationID")
                        }).
                        ToArray()).
                    ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM