How do I update an XML attribute from an MSBuild script?

梦想的初衷 提交于 2019-12-21 03:46:07

问题


I am using MSBuild and MSBuild Community Tasks (using XMLUpdate and XMLMassUpdate) to update various sections of my Web.config one thing has me stumped though. If I have:

<configuration>
    <nlog throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <targets>
            <target name="file" xsi:type="File" fileName="${logDirectory}\SomeLog.log" layout="${message}"/>
        </targets>
    </nlog> 
</configuration>

and I try to replace the fileName of the target

<XmlUpdate XmlFileName="$(BuildDir)\Builds\%(Configuration.Identity)\_PublishedWebsites\Presentation\Web.config"
           XPath="//configuration/nlog/targets/target[@fileName]"
           Value="${logDirectory}\SomeLog_%(Configuration.Identity).log" />

It reports as being unable to find anything to update, so my question is how can I get the filename attribute to updated?


EDIT: Could this be a case of namespace clashes as the NLog section defines its own namespace?


UPDATE: The posted answer declaring the name space does not work.


回答1:


The first problem is the xpath is incorrect for updating the attribute, it is currently looking for "target" nodes with an attribute called "fileName" rather than the "fileName" attribute of the a node called "target".

The xpath you want is: /configuration/nlog/targets/target/@fileName

As for the namespace issue, Preet Sangha has the correct answer for that, you need to use the namespace prefix, and this must be applied to every sub-element as well, since they are all in that namespace.

The final statement being:

<XmlUpdate
  Prefix="n"
  Namespace="http://www.nlog-project.org/schemas/NLog.xsd"
  XmlFileName="output.xml"
  XPath="//configuration/n:nlog/n:targets/n:target/@fileName"
  Value="${logDirectory}\UpdateWorked.log" />



回答2:


Here it indicates the requirement of a namespace

<XmlUpdate
   Namespace="http://schemas.microsoft.com/.NetConfiguration/v2.0"
   XmlFileName ....

can you update any other attribute?




回答3:


To complete the answer given by keeperofthesoul (I think you should give him the bounty btw) take a look at:

<XmlUpdate
  XmlFileName="web.config"
  XPath="//configuration/x:nlog/x:targets/x:target/@fileName"
  Value="%24{logDirectory}\SomeLog_%(Configuration.Identity).log"
  Prefix="x"
  Namespace="http://www.nlog-project.org/schemas/NLog.xsd"
  />

Here I'm using %24 to write out the special character $.



来源:https://stackoverflow.com/questions/1271840/how-do-i-update-an-xml-attribute-from-an-msbuild-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!