簡體   English   中英

使用C#中的LINQ-To-XML分析具有多個列表和類對象的XML數據

[英]Parse XML data with Multiple List & Class objects using LINQ-To-XML in C#

假設我要解析以下XML文件:

 <EmployeeDetails>
     <Employee>        //List of Employees
      <Id>11</Id>
      <name>a</name>
      <Dependents>    //List of Dependents of a single employee
        <Dependent>
          <name>a1</name>
          <age>50</age>      
        </Dependent>
        <Dependent>
          <name>a2</name>
          <age>52</age>      
        </Dependent>
      </Dependents>
      <Department>           //Unique per Emp
        <DeptId>1</DeptId>
        <DeptName>D1</DeptName>   
      </Department>
    </Employee>
    <Employee>
     -----
    --------
    </Employee>
   </EmployeeDetails>

以下是上述文件的結構:

public class Employee
{
  public int id {get; set;}
  public string name {get; set;}
  public List<Dependents> Dependents {get; set;}
  public Department Department {get; set;}
}

public class Dependents
{
  public string name {get; set;}
  public int age {get; set;}
}

public class Department
{
  public int DeptId {get; set;}
  public string DeptName {get; set;}
}

現在,我想解析上面的XML結構,並且能夠為Employee idname進行解析,但是我無法進一步解析。

讓我告訴你到目前為止我做了什么:

public static void ParseXml() 
{
  string xmldoc = //let's assume I've data in this string

            XDocument xdoc = new XDocument();
            xdoc = XDocument.Parse(xmldoc);

            var query = from d in xdoc.Root.Descendants("Employee")
                        select d;

            List<Employee> lsEmp = new List<Employee>();

            foreach (var q in query)
            {
                Employee obj = new Employee();
                obj.Id = Convert.ToInt32(q.Element("Id").Value);
                obj.name = q.Element("name").Value;


                obj.Department = new Department();
                obj.Dependents = new List<Dependents>();

                 // how to get data further?



               lsEmp.Add(obj);
           }

因此,我需要幫助才能從這些DependentsDepartment對象列表中解析XML數據。

按照您自己的結構,這是繼續解析所需數據的方法。

// how to get data further?
var allDependents = q.Elements("Dependents").Elements("Dependent");

foreach (var b in allDependents)
{
    Dependents d = new Dependents
    {
        age = Convert.ToInt32(b.Element("age").Value),
        name = b.Element("name").Value
    };
    obj.Dependents.Add(d);
}

obj.Department.DeptId = Convert.ToInt32(q.Element("Department").Element("DeptId").Value);
obj.Department.DeptName = q.Element("Department").Element("DeptName").Value;

注意,我已經使用.Elements("")來獲取Dependents下的所有子節點

也許這可以幫助您:

XDocument xdoc = new XDocument();
        xdoc = XDocument.Parse(xmldoc);

        var query = from d in xdoc.Root.Descendants("Employee")
                    select d;

        List<Employee> lsEmp = new List<Employee>();

        foreach (var q in query)
        {
            Employee obj = new Employee();
            obj.Id = Convert.ToInt32(q.Element("Id").Value);
            obj.name = q.Element("name").Value;


            obj.Department = new Department()
            {
                DeptName = q.Element("Department").Element("name").Value,
                DeptId = 
               Convert.ToInt32(q.Element("Department").Element("age").Value)
            };
            obj.Dependents = new List<Dependents>();


            foreach (var e in q.Element("Dependents").Elements("Dependent"))
            {
                var dependent = new Dependents()
                {
                    name = e.Element("name").Value,
                    age = Convert.ToInt32(e.Element("age").Value)
                };
                obj.Dependents.Add(dependent);
            }

            lsEmp.Add(obj);
        }

這是僅使用linq而不使用for循環的代碼

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string xml = File.ReadAllText(FILENAME);
            ParseXml(xml);

        }
        public static void ParseXml(string xml)
        {

            XDocument xdoc = XDocument.Parse(xml);

            List<Employee> employees = xdoc.Descendants("Employee").Select(x => new Employee () {
                id = (int)x.Element("Id"),
                name = (string)x.Element("Name"),
                Department = x.Elements("Department").Select(y => new Department() { DeptId = (int)y.Element("DeptId"), DeptName = (string)y.Element("DeptName")}).FirstOrDefault(),
                Dependents = x.Descendants("Dependent").Select(y => new Dependents() { age = (int)y.Element("age"),  name = (string)y.Element("name")}).ToList()
            }).ToList();
        }


    }
    public class Employee
    {
        public int id { get; set; }
        public string name { get; set; }
        public List<Dependents> Dependents { get; set; }
        public Department Department { get; set; }
    }

    public class Dependents
    {
        public string name { get; set; }
        public int age { get; set; }
    }

    public class Department
    {
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM