为什么C#XDocument.Descendants()不起作用
本文关键字:不起作用 Descendants C#XDocument 为什么 | 更新日期: 2023-09-27 18:25:23
我的XML:示例
<data>
<Balance>
<LocationName>Locatie 1</LocationName>
<Latitude>39.74</Latitude>
<Longitude>-104.99</Longitude>
<RTI>
<Container>12</Container>
<Pallet>54</Pallet>
</RTI>
</Balance>
// Lots more Balance nodes
</data>
我的代码:
XDocument doc = XDocument.Load(HttpContext.Current.Request.PhysicalApplicationPath + "/Content/saldotracking.xml");
var balances = doc.Descendants("Data");
foreach (var b in balances)
{
if (b.Element("LocationName").Value == id)
{
this.LocationName = b.Element("LocationName").Value;
this.Longitude = Convert.ToDouble(b.Element("Longitude").Value);
this.Latitude = Convert.ToDouble(b.Element("Latitude").Value);
this.pallets = Convert.ToInt16(b.Element("RTI").Element("Pallet").Value);
this.containers = Convert.ToInt16(b.Element("RTI").Element("Container").Value);
}
}
根据调试器的说法,值"b"包含整个XML文档,而不是单个Balance节点。我做错了什么?我正在尝试读取Balance节点的所有子节点,该节点的LocationName节点的值等于String参数。有人能帮忙吗?
根据变量名称和用法判断,您没有正确使用Descendants(string XName)
。
public IEnumerable<XElement> Descendants( XName name )
按文档顺序返回此文档或元素的子代元素的筛选集合只有具有匹配
XName
的元素才会包含在集合中。
doc.Descendants("Data")
将为您提供具有Data
的元素名称的所有子体,而不是Data
元素的所有子体。
我怀疑你想要:
var balances = doc.Descendants("Balance");
意思是"给我元素名称为"Balance"
的文档元素的所有子体
如果您想读取Balance节点的子节点,请使用以下语句
var balances=单据。后代("平衡");
它将加载带有"Balances"的所有元素