有没有一种方法可以检查C#Linq中的元素以查看值是什么?

时间:2020-02-13 21:42:49

标签: c# xml linq-to-xml

可以为我的程序提供两种不同类型的xml文件。区别的唯一方法是查看它来自什么设备。我如何从该xml文档中获取设备名称?

<?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
    <System Name="Local">
        <SysInfo>
            <Devices>
                <RealMeasurement>
                    <Hardware></Hardware>
                    <Device Type="MultiDevice">
                        <DriverBuffSizeInSec>5</DriverBuffSizeInSec>
                        <Card Index="0">
                            <DeviceName>SIRIUSi</DeviceName>
                            <DeviceSerialNumber>D017F09216</DeviceSerialNumber>
                            <FirmwareVersion>7.3.45.75</FirmwareVersion>
                            <VCXOValue>8802</VCXOValue>
                        </Card>
                    </Device>
                </RealMeasurement>
              </Devices>
            </SysInfo>
         </System>
   </DataFileSetup>

简单的

var deviceType = xdoc.Element("DeviceName").Value;

由于那里什么都没有而出错,或者如果我删除.Value,它只是空的。

是否有一种简单的方法来获取该值?

2 个答案:

答案 0 :(得分:1)

请尝试以下操作。

c#

void Main()
{
    const string fileName = @"e:\temp\device.xml";

    XDocument xdoc = XDocument.Load(fileName);
    Console.WriteLine(xdoc.Descendants("DeviceName").FirstOrDefault()?.Value);
}

输出

SIRIUSi

答案 1 :(得分:0)

在这种情况下,我喜欢使用字典:

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

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

            Dictionary<string, XElement> dict = doc.Descendants("Device")
                .GroupBy(x => (string)x.Descendants("DeviceName").FirstOrDefault(), y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}