在没有命名空间的情况下运行 linq-to-XML 操作
我的一个项目中有很多这样的代码(在我知道如何使用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 格式。
I have a lot of code like this in one of my projects (from before I knew how to use 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;
}
My question is: is there a way to run these queries without having to pass around the namespace? Is there a way to say xml.Descendants("EditorialReview")
and have it work even if that element has a namespace attached?
Needless to say, I have no control over the XML format returned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
否,
Descendants("EditorialReview")
选择非命名空间中具有本地名称EditorialReview
的元素,因此该调用不会选择命名空间中的任何元素。但是,对于您的方法getValue
,您可以消除XNamespace
参数ns
并改为使用public static string getValue(XElement el, XName name)
然后简单地调用它,例如getValue(el, ns + "Source")
。No,
Descendants("EditorialReview")
selects elements with local nameEditorialReview
in no namespace so that call does not select any elements which are in a namespace. However for your methodgetValue
you could eliminate theXNamespace
argumentns
and instead usepublic static string getValue(XElement el, XName name)
and then simply call it as e.g.getValue(el, ns + "Source")
.