且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用LINQ-to-XML获得元素之后的第一个元素?

更新时间:2023-11-07 15:05:22

您要使用Descendants轴方法,然后调用FirstOrDefault扩展方法以获取第一个元素.

You want to use the Descendants axis method and then call the FirstOrDefault extension method to get the first element.

这是一个简单的例子:

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        String xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
            <smartForm idCode=""customersMain"">
                <title>Customers Main222</title>
                <description>Generic customer form.</description>
                <area idCode=""generalData"" title=""General Data"">
                <column>
                    <group>
                    <field idCode=""anrede"">
                        <label>Anrede</label>
                    </field>
                    <field idCode=""firstName"">
                        <label>First Name</label>
                    </field>
                    <field idCode=""lastName"">
                        <label>Last Name</label>
                    </field>
                    </group>
                </column>
                </area>
                <area idCode=""address"" title=""Address"">
                <column>
                    <group>
                    <field idCode=""street"">
                        <label>Street</label>
                    </field>
                    <field idCode=""location"">
                        <label>Location</label>
                    </field>
                    <field idCode=""zipCode"">
                        <label>Zip Code</label>
                    </field>
                    </group>
                </column>
                </area>
            </smartForm>";

        XElement element = XElement.Parse(xml)
            .Descendants()
            .FirstOrDefault();
    }
}