我有这个代码。这里还有一个 XML 示例。对于任何混淆,我深表歉意
<object type="node" >
<property name="id" value="1" />
<property name="name" value="ossvc06_node1" />
<property name="port_id" value="50050768014062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768013062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768011062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768012062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="hardware" value="8G4" />
<property name="iscsi_name" value="iqn.1986-03.com.ibm:2145.ossvc06.ossvc06node1" />
<property name="iscsi_alias" value="" />
<property name="failover_active" value="no" />
<property name="failover_name" value="ossvc06_node2" />
<property name="failover_iscsi_name" value="iqn.1986- .com.ibm:2145.ossvc06.ossvc06node2" />
<property name="failover_iscsi_alias" value="" />
<property name="front_panel_id" value="115286" />
</object>
在输入文件中有两个“节点”类型的对象,每个对象都有不同的属性标签值。
在这段代码中,我在传入的 XML 中查找所有类型为“node”的对象。其中有 2 个。'var nodes' 语句计算正确。在调试器中,我可以看到两个 XElement,它们的类型和元素列表中的元素似乎是正确的。但是,获取元素并将它们分配给列表的语句具有来自 XML 中“节点”类型的两个对象的 ChildElements,我不知道为什么。
//load the input file
XDocument xdoc = XDocument.Load(_InputFile);
//get the object of type 'node'
//this code gives the results expected
// in the debugger each XElement appears to have the proper value and childElements
var nodes = from node in xdoc.Descendants("object")
where node.Attribute("type").Value == "node"
select node;
foreach (XElement nodelement in nodes)
{
// problem happens here, the child elements from both nodes get assigned to the list
List<XElement> nodeles = nodelement.Elements().ToList();
Node node = NodeFactory(nodelement);
// now assign the node to the correct IO group
var iogrp = SVCClusters[0].IOGroups.Where(io => io.Name == node.IOGroupName);
if (iogrp.FirstOrDefault().FirstNode == null) { iogrp.FirstOrDefault().FirstNode = node; }
else { iogrp.FirstOrDefault().SecondNode = node; }
}