繁体   English   中英

当根元素具有通过XDocument的属性时,搜索XML元素问题

[英]Searching XML elements issue when root element has attributes via XDocument

我想从项目文件(* .csproj文件)中搜索以下元素

<ItemGroup>
    <Reference Include="C.ClassLibrary3, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Lib\C.ClassLibrary3.dll</HintPath>
    </Reference>
    <Reference Include="System" />
  </ItemGroup>

项目文件在下面,请注意Project元素的属性:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
    <Reference Include="C.ClassLibrary3, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Lib\C.ClassLibrary3.dll</HintPath>
    </Reference>
    <Reference Include="System" /> 
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup> 
</Project>

代码如下:

var projectFile = XDocument.Load(projectFilePath);               
var itemGroup = projectFile
.Descendants("ItemGroup")
.Where(x =>x.Elements("Reference").Elements("HintPath").Any())
.ToList();

问题在于,上面的代码仅在将project元素更改为以下内容(删除所有属性)后才能起作用:

<Project>  

我应该如何修复代码,以便代码可以正常工作并且项目仍是原始项目?

更新:

当我向文件添加新元素时,它会自动添加名称空间

提前致谢。

尝试如下使用XElement,确保为查询的每个元素指定名称空间:

XElement xml= XElement.Load("file.xml"); 
XNamespace ns= xml.Name.Namespace; 
var groups = xml.Elements(ns+ "ItemGroup"); 

如果您不想在所有地方使用ns ,则可以加载xml,遍历所有元素并将namespace属性设置为空字符串,或者可以实现自定义方法来为您提供正确的名称:

public static XNamespace ns =  @"http://schemas.microsoft.com/developer/msbuild/2003";

public static XName MsElementName(string baseName)
{
    return ns + baseName;   
}

并按以下方式使用它:

var groups = xml.Elements(MsElementName("ItemGroup")); 

您的Project元素中有一个命名空间,因此需要在元素名称中指定它:

XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";

var itemGroup = projectFile
               .Descendants(ns +"ItemGroup")
               .Where(x =>x.Elements(ns + "Reference").Elements(ns +"HintPath").Any())
               .ToList();

有关更多详细信息,请参见How to: Write Queries on XML in Namespaces

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM