使用XElement.Elements方法,可以找到具有通配符命名空间但名称相同的元素吗? [英] Using the XElement.Elements method, can I find elements with wildcard namespace but the same name?

查看:35
本文介绍了使用XElement.Elements方法,可以找到具有通配符命名空间但名称相同的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试对XML文档进行简单的解析.拉出下面两个PropertyGroup的最简单方法是什么?

Trying to do a simple parse of an XML document. What's the easiest way to pull out the two PropertyGroups below?

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     1
  </PropertyGroup>
  <PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     2
  </PropertyGroup>
</Project>

我一直在尝试使用XElement.Elements(XName),但要这样做,我需要给PropertyGroup加上xmlns前缀.问题是我不在乎名称空间,如果将来更改它,我仍然希望检索所有PropertyGroup.

I have been trying to use XElement.Elements(XName) but to do so I need to prefix PropertyGroup with the xmlns. The issue is that I don't care about the name space and if it changes in future I would still like all PropertyGroups to be retrieved.

 var xml = XElement.Load(fileNameWithPath);
 var nameSpace = xml.GetDefaultNamespace();

 var propertyGroups= xml.Elements(nameSpace + "PropertyGroup");

您可以在此代码上进行改进,以使我不需要以nameSpace开头吗?我知道我基本上可以重新实现Elements方法,但是我希望有某种方法可以传递通配符名称空间?

Can you improve on this code such that I don't need to prepend with nameSpace? I know I can essentially just reimplement the Elements method but I was hoping there was some way to pass a wildcard namespace?

谢谢

Gavin

推荐答案

这对您有用吗?

xml.Elements().Where(e => e.Name.LocalName == "PropertyGroup")

这篇关于使用XElement.Elements方法,可以找到具有通配符命名空间但名称相同的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆