查询的XDocument与xmlns属性(命名空间) [英] Query XDocument with xmlns attribute (namespace)

查看:1503
本文介绍了查询的XDocument与xmlns属性(命名空间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试查询从视觉工作室* .csproj的文件元素。我创建了一个简单的例子来说明这个问题:

  //工作
串XML1 = @<项目ToolsVersion ='4.0'>
<的ItemGroup标签='Usings'>
<参考包括='系统'/>
<参考包括='的System.Xml'/ >
< /&的ItemGroup GT;
< /项目>中;
//不工作
串XML2 = @<项目ToolsVersion ='4.0'的xmlns =HTTP://schemas.microsoft.com/developer/msbuild/2003'>
<的ItemGroup标签='Usings'>
<参考包括='系统'/>
<参考包括='的System.Xml'/>
< /的ItemGroup> ;
< /项目>中;

的XDocument DOC = XDocument.Parse(XML2);

的foreach
{
Console.WriteLine(元)(以doc.Descendants(的ItemGroup)的XElement元);
}



XML1工作正常的字符串,XML2不返回任何东西。这些字符串之间的唯一区别是在文档根xmlns属性。



我如何查询包含的xmlns属性的文件?
当XML文档包含xmlns属性为什么是一个问题?


解决方案

当一个XML文档包含xmlns属性为什么是一个问题?




这不,如果你明白是什么意思:)基本上你'已经应用了的默认的命名空间的 http://schemas.microsoft.com/developer/ URI的MSBuild / 2003 的所有元素。因此查询时,你需要指定过该命名空间。幸运的是,LINQ到XML使这很简单:

 的XNamespace NS =htt​​p://schemas.microsoft.com/developer/的MSBuild / 2003; 
的XDocument DOC = XDocument.Parse(XML2);
的foreach
{
Console.WriteLine(元)(以doc.Descendants(NS +的ItemGroup)的XElement元);
}


I try to query elements from an visual studio *.csproj file. I created a short example to illustrate the problem:

    // 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);
    }

The string xml1 works fine, xml2 doesn't return anything. The only difference between those strings is xmlns attribute in the document root.

How do i query documents containing xmlns attributes? Why is it a problem when a xml document contains an xmlns attribute?

解决方案

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

It's not, if you understand what it means :) Basically you've applied a default namespace URI of "http://schemas.microsoft.com/developer/msbuild/2003" to all elements. So when querying, you need to specify that namespace too. Fortunately, LINQ to XML makes that really simple:

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);
}

这篇关于查询的XDocument与xmlns属性(命名空间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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