【发布时间】: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