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

问题描述 投票:0回答:2

我的程序可以得到两种不同类型的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,它只是空的。

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

c# xml linq-to-xml
2个回答
2
投票

请尝试以下操作。

c#

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

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

输出

SIRIUSi

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());
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.