加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用xmlns属性(命名空间)查询XDocument

发布时间:2020-12-15 06:33:21 所属栏目:百科 来源:网络整理
导读:我尝试从visual studio * .csproj文件查询元素.我创建了一个简单的例子来说明问题: // Working string xml1 = @"Project ToolsVersion='4.0' ItemGroup Label='Usings' Reference Include='System' / Reference Include='System.Xml' / /ItemGroup /Project
我尝试从visual studio * .csproj文件查询元素.我创建了一个简单的例子来说明问题:
// Working
    string xml1 = @"<Project ToolsVersion='4.0'>
                      <ItemGroup Label='Usings'>
                        <Reference Include='System' />
                        <Reference Include='System.Xml' />
                      </ItemGroup>
                    </Project>"; 
    // Not working
    string xml2 = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
                      <ItemGroup Label='Usings'>
                        <Reference Include='System' />
                        <Reference Include='System.Xml' />
                      </ItemGroup>
                    </Project>";

    XDocument doc = XDocument.Parse(xml2);

    foreach (XElement element in doc.Descendants("ItemGroup"))
    {
        Console.WriteLine(element);
    }

字符串xml1工作正常,xml2不返回任何东西.这些字符串之间的唯一区别是文档根目录中的xmlns属性.

如何查询包含xmlns属性的文档?
当xml文档包含xmlns属性时,为什么会出现问题?

解决方法

Why is it a problem when a xml document contains an xmlns attribute?

这不是,如果你明白这是什么意思:)基本上你已经应用了所有元素的默认命名空间URI“http://schemas.microsoft.com/developer/msbuild/2003”.所以当查询时,你也需要指定这个命名空间.幸运的是,LINQ to XML使得它非常简单:

XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument doc = XDocument.Parse(xml2);
foreach (XElement element in doc.Descendants(ns + "ItemGroup"))
{
    Console.WriteLine(element);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读