Question

I want to search the element below from a project file (*.csproj file)

<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>

The project file is below, please note the attributes of Project element.:

<?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>

The code is below:

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

The problem is that the code above only works after the project element is changed to below (remove all attributes.):

<Project>  

What should I do fix the code so the code works and the project remains the original?

Update:

When I add a new element to the file, it automatically add a namespace

Thanks in advance.

Was it helpful?

Solution

Try using XElement as following, make sure you specify the namespace for each element you query:

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

if you don't want to use ns everywhere, you can load the xml, go through all elements and set the namespace attribute to empty string, or you can implement custom method to give you the correct name:

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

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

and use it like following:

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

OTHER TIPS

You have a namespace in your Project element.So you need to specify it within the element name:

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

See How to: Write Queries on XML in Namespaces for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top