2011-04-08 97 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