Skip to main content
 首页 » 编程设计

c#之在C#中的XML中获取Parent二级节点值

2024年02月06日9qlqwjy

我有如下示例所示的 XML -

<?xml version="1.0" encoding="UTF-8"?> 
<Model> 
  <Part Id="0"> 
    <Specs> 
      <Spec Id = "100" name="SpecNode"> 
      </Spec> 
    </Specs> 
  </Part> 
</Model> 

这是我的 XML 示例说明,因此请忽略任何输入错误。

所以在这个 XML 中,我能够检索 Spec 作为 XPathNodeIterator 对象。所以现在我想去 Part 节点并获取它的 Id 属性值。因为我拥有的是 XPathNodeIterator 对象,它指向 Spec 和 Part 节点位于上面两层。

因此,请指导我进行代码更改以实现此要求。

她是我的代码片段..

System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument("my.xml"); 
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); 
XPathNodeIterator nodes = xmlNav.Select(XPathExpression.Compile(@"//Part/Specs/Spec[@name="SpecNode"])) 

上面的代码示例为我提供了节点对象。所以我现在的要求是获取比它高两层的Part节点的Id值。

请您参考如下方法:

您可以使用以下 LINQ 检索 Part-node 的 Id-attribute:

const string file = @"D:\Temp\file.xml"; 
 
// Load the file. 
XDocument doc = XDocument.Load(file); 
 
// Retrieve the attribute selecting the Part-Element and then its Id-attribute. 
XAttribute partAttribute = doc.Root.Descendants("Part").Select(element => element.Attribute("Id")).FirstOrDefault(); 
 
// Call partAttribute.Value to retrieve its' value. 
Console.WriteLine(partAttribute.Value); 
Console.Read(); 

输出:0。

请注意,如果 Part-Element 不存在,将在调用 partAttribute.Value 时抛出 NullReferenceException。如果 Part-Element 存在但 Id 不存在,也会发生同样的情况。使用 if(partAttribute != null) 确定该值是否存在。


如果您将获得很多部分节点,您可以使用 KeyValuePairs 按 ID 对它们进行排序:

List<KeyValuePair<int, XElement>> partNodesWithIDValue = new List<KeyValuePair<int, XElement>>(); 
 
// Get a list of all Part-nodes where an ID exists. 
List<XElement> partNodes = doc.Root.Descendants("Part").Where(element => element.Attribute("Id") != null).ToList(); 
 
// Sort the XElements according to their ID-value. 
foreach (XElement partNode in partNodes) 
{ 
    KeyValuePair<int, XElement> elementWithAttribID = new KeyValuePair<int, XElement>(int.Parse(partNode.Attribute("Id").Value), partNode); 
    partNodesWithIDValue.Add(elementWithAttribID); 
} 
 
// Get a list of all Part-elements where the ID = 1. 
List<XElement> partNodesWithID1 = partNodesWithIDValue.Where(kvp => kvp.Key == 1).Select(kvp => kvp.Value).ToList(); 

既然您想保留原始代码,只需简单更改 XPath 即可:

XPathNodeIterator nodes = xmlNav.Select(XPathExpression.Compile(@"//Part[@Id]")); 

//Part[@Id]://Part 选择所有名为Part 的节点。添加 [@Id] 使其仅选择那些具有 Id 属性的部分节点。