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属性的文档? 解决方法
这不是,如果你明白这是什么意思:)基本上你已经应用了所有元素的默认命名空间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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |