使用LINQ从XML获取XElement

时间:2015-06-01 19:31:33

标签: xml linq

我已将文件路径加载到XDocument中。我试图获得XElement但没有找到任何好的来源。

是否可以使用LINQ to XML获取XElement标记?

XML 如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<transactionBlock>
    <trans aux ID="1849" company ID="ABC">
        <T.2.12.0>
            <event TS>16:02:56Z</event TS>
            <equipment ID="0105449160" mobile Type="2" equip Type="tractor"/>
            <driver ID>002</driver ID>
        </T.2.12.0>
    </trans>
    <trans aux ID="1854" company ID="XYZ">
        <T.2.06.0>
            <event TS>16:07:50Z</event TS>
            <equipment ID="0105449160" mobile Type="3"/>
            <driver ID>002</driver ID>
        </T.2.06.0>
    </trans>
</transactionBlock>

3 个答案:

答案 0 :(得分:1)

我发现使用XPath表达式更容易在XML元素中导航,因为它可以处理过滤器和更直接的现有结构方法。在这种情况下,您可以这样做:

var doc = XDocument.Parse(@"<?xml version='1.0' encoding='UTF-8'?>
    <transactionBlock>
        <trans auxID='1849' companyID='ABC'>
            <T.2.12.0>
                <eventTS>16:02:56Z</eventTS>
                <equipment ID='0105449160' mobileType='2' equipType='tractor'/>
                <driverID>002</driverID>
            </T.2.12.0>
        </trans>
        <trans auxID='1854' companyID='XYZ'>
            <T.2.06.0>
                <eventTS>16:07:50Z</eventTS>
                <equipment ID='0105449160' mobileType='3'/>
                <driverID>002</driverID>
            </T.2.06.0>
        </trans>
    </transactionBlock>");

var transactions = doc.XPathSelectElements("/transactionBlock/trans/*");
foreach (var transaction in transactions)
{
    Console.WriteLine(transaction.Name);
}

答案 1 :(得分:0)

我希望它会帮助某人:

解决方案:

       var doc = XDocument.Load(File);
        var transactions = doc.Root.Elements().Select(t => t.Elements().First());

        foreach (var transaction in transactions)
        {
            var id = transaction.Name.LocalName;
            Console.WriteLine(id);
        }

输出:

T.2.12.0

T.2.06.0

答案 2 :(得分:0)

IEnumerable<string> transactions = doc.Root.Descendants("trans").Where(x => string.Compare(x.Name.LocalName, "trans") == 0 && x.HasElements).Select(x => (x.FirstNode as XElement).Name.LocalName);
                foreach (var item in transactions)
                {
                    Console.WriteLine(item);     
                }