[英]Run linq-to-XML operations without namespace
我的一个项目中有很多这样的代码(在我不知道如何使用yield return之前):
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格式。
不, Descendants("EditorialReview")
在没有名称空间的情况下选择具有本地名称EditorialReview
元素,以便调用不会选择在名称空间中的任何元素。 但是,对于您的方法getValue
您可以消除XNamespace
参数ns
,而使用public static string getValue(XElement el, XName name)
,然后简单地将其调用为例如getValue(el, ns + "Source")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.