Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# to find nodes within .csproj files

Tags:

c#

xml

I'm having trouble trying to select a particular node from a .csproj file I've read in as a XDocument.

XDocument xmldoc = XDocument.Load("The full path of the .csproj file");

This loads the .csproj file into a XDocument without issue. I've tried Descendants, Elements, etc etc to try to get TheNodeIWant and its value, but cannot figure out why I keep getting no results.

<?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <TheNodeIWant>The String I Want </TheNodeIWant>
        </PropertyGroup>
        <PropertyGroup>
        .......
        </PropertyGroup>
    </Project>

How can I select TheNodeIWant and retrieve its value?

like image 509
tnw Avatar asked Dec 20 '22 08:12

tnw


1 Answers

see https://stackoverflow.com/a/4171468/1301310

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"c:\test.txt");

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
XmlNode node = xmldoc.SelectSingleNode("//msbld:TheNodeIWant", ns);

if (node != null)
{
    MessageBox.Show(node.InnerText);
}
like image 117
Gina Marano Avatar answered Feb 06 '23 21:02

Gina Marano