2011-04-08 102 views
2

我有很多這樣的代碼在我的項目之一(從之前,我知道如何使用的yield return)運行LINQ到XML操作:沒有命名空間

public EditorialReviewDTO[] GetEditorialReviews(string URL) { 
     XDocument xml = XDocument.Load(URL); 
     XNamespace ns = xml.Root.Name.NamespaceName; 
     List<EditorialReviewDTO> result = new List<EditorialReviewDTO>(); 

     List<XElement> EdRevs = xml.Descendants(ns + "EditorialReview").ToList(); 
     for (int i = 0; i < EdRevs.Count; i++) { 
      XElement el = EdRevs[i]; 
      result.Add(new EditorialReviewDTO() { Source = XMLHelper.getValue(el, ns, "Source"), Content = Clean(XMLHelper.getValue(el, ns, "Content")) }); 
     } 

     return result.ToArray(); 
    } 

    public static string getValue(XElement el, XNamespace ns, string name) { 
     if (el == null) return String.Empty; 

     el = el.Descendants(ns + name).FirstOrDefault(); 
     return (el == null) ? String.Empty : el.Value; 
    } 

我的問題是:是否有一種方法來運行這些查詢沒有必須傳遞命名空間?有沒有辦法說xml.Descendants("EditorialReview")並且即使該元素具有附加的命名空間也能正常工作?

不用說,我無法控制返回的XML格式。

回答

1

不,Descendants("EditorialReview")在沒有命名空間中選擇本地名稱爲EditorialReview的元素,以便調用不會選擇位於命名空間中的任何元素。但是,對於您的方法getValue,您可以消除XNamespace自變量ns,而改爲使用public static string getValue(XElement el, XName name),然後簡單地稱其爲例如。 getValue(el, ns + "Source")

+0

夠公平的,謝謝! – 2011-04-08 17:11:05