0

我想使用 MSBuild 将自定义 xml 元素插入 web.config。在网上查了一下,我找到了这样的解决方案:

1) 将元素存储在 projectextensions 中的 .build 文件中

<ProjectExtensions>
 <CustomElement name="CustomElementName">
  ...
 </CustomElement>
</ProjectExtensions>

2) 使用 GetValue 检索元素

<Target name="ModifyConfig">
<XmlFile.GetValue Path="$(MSBuildProjectFullPath)"
               XPath="Project/ProjectExtensions/CustomElement[@name='CustomElementName']">
            <Output TaskParameter="Value" PropertyName="CustomElementProperty"/>
</XmlFile.GetValue>
</Target>

这将不起作用,因为我需要引用 .build 项目正在使用的命名空间来查找所需的元素(使用 XPath Visualizer 检查了 .build 文件)。所以,我寻找进一步的解决方案并得出这个结论:

<ItemGroup>
        <XmlNamespace Include="MSBuild">
            <Prefix>msb</Prefix>
            <Uri>http://schemas.microsoft.com/developer/msbuild/2003</Uri>
        </XmlNamespace>
</ItemGroup>

<Target name="ModifyConfig">
<XmlFile.GetValue Path="$(MSBuildProjectFullPath)" Namespaces="$(XmlNamespace)"
               XPath="/msb:Project/msb:ProjectExtensions/msb:CustomElement[@name='CustomElementName']"
                 >
            <Output TaskParameter="Value" PropertyName="CustomElementProperty"/>
</XmlFile.GetValue>
</Target>

但由于某种原因,无法识别命名空间 - MSBuild 报告以下错误:

C:...\mybuild.build(53,9): error : 发生任务错误。C:...\mybuild.build(53,9): 错误:消息 = 未定义命名空间前缀“msb”。

我尝试了一些以不同方式引用它的变体,但都没有奏效,而且也没有太多关于正确地在线引用这些命名空间的方法。你能告诉我我做错了什么以及如何正确地做吗?

4

1 回答 1

1

我建议使用来自MSBuild 社区任务的自定义任务,该任务称为XmlMassUpdate将自定义 XML 元素插入 xml 文件。

<XmlMassUpdate 
ContentFile="web.config" 
SubstitutionsFile="changes.xml" 
ContentRoot="/configuration/system.web" 
SubstitutionsRoot="/system.web" /> 

您也可以直接在项目文件中引用 XML,如下所示:

<XmlMassUpdate ContentFile="web.config" ContentRoot="/configuration/system.web"
    NamespaceDefinitions="msb=http://schemas.microsoft.com/developer/msbuild/2003"
    SubstitutionsFile="$(MSBuildProjectFullPath)"
    SubstitutionsRoot="/msb:Project/msb:ProjectExtensions/msb:system.web" />

但是,您的问题似乎表明您在获取 XML 值而不是更改它们时遇到了问题。提到的库也有XmlQuery任务,它从 XML 文件中读取值并根据这些值填充参数。

于 2010-03-29T09:03:22.530 回答