【问题标题】:Is there a way to check element in C# Linq to see what the value is?有没有办法检查 C# Linq 中的元素以查看值是什么?
【发布时间】:2020-02-13 21:42:49
【问题描述】:

我的程序可以有两种不同的 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 它只是空。

有没有简单的方法来获取这个值?

【问题讨论】:

  • 你试过 xpath 吗? //DataFileSetup/System/SysInfo/Devices/RealMeasurement/Device/Card/DeviceName
  • 这两个xml有不同的结构吗? DeviceName 的 xpath 会有所不同吗?一个万无一失的解决方案取决于此。
  • 您可以检查.Descendants("DeviceName").Any();是否存在并获取值。
  • 值会给出异常。而是强制转换: var deviceType = (string)xdoc.Element("DeviceName");在瘦的情况下,我会使用后代: List deviceNames = xdoc.Descendents("DeviceName").ToList();

标签: c# xml linq-to-xml


【解决方案1】:

请尝试以下方法。

c#

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

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

输出

SIRIUSi

【讨论】:

    【解决方案2】:

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

    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());
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2016-10-10
      • 2020-11-01
      • 2020-02-04
      • 2020-09-15
      • 1970-01-01
      相关资源
      最近更新 更多