使用LINQ to XML访问xml元素

时间:2014-01-15 00:37:09

标签: c# linq linq-to-xml

我有一个像这样的xml文档,我需要访问“employees”,“employee”元素,所以我试图使用linq的XDocument类来获取employee元素,但它总是返回空值。

示例xml:

<organization>
   <metadata>
   </metadata>
   <main>
     <otherInfo>
     </otherInfo>
     <employeeInfo>
      <employees>
        <employee>
           <id>1</id>
           <name>ABC</name>
        </employee>
        <employee>
           <id>2</id>
           <name>ASE</name>
        </employee>
        <employee>
           <id>3</id>
           <name>XYZ</name>
        </employee>
      </employees>
     </employeeInfo>
    </main>
</organization>

C#代码:

XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = from d in xDoc.Descendants("employeeInfo")
               from ms in d.Elements("employees")                                   
               from m in ms.Elements("employee")
               select m;

3 个答案:

答案 0 :(得分:1)

这取决于您需要什么信息。您的select返回IEnumerable列表。 此代码将打印出每个员工

string xmlString = @"<organization>
                           <metadata>
                           </metadata>
                           <main>
                             <otherInfo>
                             </otherInfo>
                             <employeeInfo>
                              <employees>
                                <employee>
                                   <id>1</id>
                                   <name>ABC</name>
                                </employee>
                                <employee>
                                   <id>2</id>
                                   <name>ASE</name>
                                </employee>
                                <employee>
                                   <id>3</id>
                                   <name>XYZ</name>
                                </employee>
                              </employees>
                             </employeeInfo>
                            </main>
                        </organization>";

        XDocument xDoc = XDocument.Parse(xmlString);
        var allEmployees = from d in xDoc.Descendants("employeeInfo")
           from ms in d.Elements("employees")                                   
           from m in ms.Elements("employee")
           select m;

        foreach (var emp in allEmployees) {
            Console.WriteLine(emp);
        }
        Console.Read();

答案 1 :(得分:1)

XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = (from r in xDoc.Descendants("employee")
                   select new
                   {
                       Id = r.Element("id").Value,
                       Name = r.Element("name").Value
                   }).ToList();

foreach (var r in allEmployees)
{
    Console.WriteLine(r.Id + " " + r.Name);
}

答案 2 :(得分:1)

只需使用Descendants("Employee");

即可
XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = xDoc.Descendants("employee").ToList();