【问题标题】:SelectNodes() call on XMLDocument returning nothing对 XMLDocument 的 SelectNodes() 调用不返回任何内容
【发布时间】:2017-02-19 21:48:47
【问题描述】:

我有以下简单的 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 文件顶部的 cmets,我只尝试了 /Project,只是 Project,但我似乎无法理解出了什么问题。我看过其他帖子,但看不到我的问题。任何想法?谢谢!

【问题讨论】:

  • 丢失尾部斜杠以使其成为/Project/PropertyGroup 或实际选择孩子:/Project/PropertyGroup/*
  • 抱歉,我应该提到我也尝试过 "xDoc.SelectNodes("/Project"),但即使这样也没有任何效果。
  • 您在手表中检查过 xDoc 吗?它包含您的期望吗?
  • 是的,那里有文档,根为#document。不过,我不知道出了什么问题。
  • 啊,命名空间...@see stackoverflow.com/questions/4171451/…

标签: c# .net xml xmldocument selectnodes


【解决方案1】:

您正在查询具有命名空间的文档,因此您还需要在代码中解决该问题。所以使用一个命名表,在某个命名空间下注册 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);

或类似的。

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多