2014-04-17 16 views
2

下面的代碼正在.NET框架4.5上正確編譯。無法在System.Xml.Linq.XNode中找到'ChildNodes'

public void SetProperties(System.Xml.XmlNode properties) 
     { 
       int tempFor1 = properties.ChildNodes.Count; 
     } 

由於System.Xml.XmlNode類型現在是過時的.NetCore所以我System.Xml.Linq.XNode取而代之。 但是,當我嘗試在.NetCore上構建它時,發現「ChildNodes」錯誤未找到。

這裏是更新的代碼。

public void SetProperties(System.Xml.Linq.XNode properties) 
     { 
       int tempFor1 = properties.ChildNodes.Count; 
     } 

獲得子節點數的可能解決方案是什麼?

回答

1

如果您的XNode是一個元素,然後將其轉換爲XElement。然後它會有一個Elements()方法,你可以使用標準的Linq對象來Count()。如果你沒有看到count()函數,確保添加

using System.Linq; 
+0

沒有元素屬性,而不是用相同名稱的功能。它沒有計數功能 – user3524034

+0

正確 - 這是一個功能。但好消息是,沒有參數的函數會返回完整的集合,並且您可以Count()。 – Zaccone

2

嘗試這樣的事情...

public void SetProperties(System.Xml.Linq.XNode properties) 
{ 
    var element = properties as XElement; 
    int tempFor1 = 0; 
    if (element != null) 
    { 
     tempFor1 = element.Elements().Count(); 
    } 
}