Search code examples
c#.netxmlxmldocumentselectnodes

SelectNodes() call on XMLDocument returning nothing


I have the following simple XML File:

    <?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit http://go.microsoft.com/fwlink/?LinkID=208121. 
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>False</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <publishUrl>E:\PublishTest</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
  </PropertyGroup>
</Project>

And am trying to change the value of one of the elements by doing the following:

XmlDocument xDoc = new XmlDocument();
xDoc.Load(fullPathToPortalPublishSettings);

// Change the publish url to be the one we want
var a = xDoc.SelectNodes("/Project/PropertyGroup");

But it always bombs out. I've removed the comments at the top of the XML file, I've tried just /Project, just Project, and I just can't seem to understand what is going wrong. I've looked at other posts, but don't see what is wrong with mine. Any idea? Thanks!


Solution

  • You're querying a document that has a namespace so you need to address that in your code as well. so use a nametable, register the msbuild namespace under some namespace and use that like so:

    XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
    manager.AddNamespace("msb", "http://schemas.microsoft.com/developer/msbuild/2003");
    var nodes = xDoc.SelectNodes("//msb:Project/msb:PropertyGroup", manager);
    

    or similar.