SelectNodes()调用XMLDocument什么都不返回

时间:2016-10-11 11:01:33

标签: c# .net xml xmldocument selectnodes

我有以下简单的XML文件:

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

我正在尝试通过执行以下操作来更改其中一个元素的值:

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

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

但它总是爆炸。我已经删除了XML文件顶部的评论,我只是尝试/Project,只是Project,而我似乎无法理解将要发生的事情错误。我查看了其他帖子,但没有看到我的错误。任何的想法?谢谢!

1 个答案:

答案 0 :(得分:2)

您正在查询具有命名空间的文档,因此您还需要在代码中解决该问题。所以使用一个名称表,在某些名称空间下注册msbuild名称空间并使用它:

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

或类似。