tags:

views:

562

answers:

2

Hi,

Is there a way to add an attribute to an xml node (which I have the xpath of) using nant? Tried xmlpoke but it looks like it can only update existing attributes.

thanks.

+1  A: 

XmlPoke will definitely not work because the xpath must match something in the first place to be able to replace it.

The only way I know of doing this is to create your own task that would allow you to add data to an xml file. These new tasks can either be build separately and added to NAnt by copying dlls into NAnt\bin folder, or by extending NAnt directly from your build files

The information to get you started is found on <script/> Task

If you happen to make this task generic enough, it might be good to try to submit it to NAntContrib so everyone benefits.

earlNameless
A: 

I made something similar recently. This is for inserting nodes, but should be easily changed.

<script language="C#" prefix="test" >
        <references>
            <include name="System.Xml.dll" />
        </references>
        <code>
            <![CDATA[
              [TaskName("xmlinsertnode")]
              public class TestTask : Task {
                #region Private Instance Fields
                private string _filename;
                private string _xpath;
                private string _fragment;
                #endregion Private Instance Fields

                #region Public Instance Properties
                [TaskAttribute("filename", Required=true)]
                public string FileName {
                    get { return _filename; }
                    set { _filename = value; }
                }

                [TaskAttribute("xpath", Required=true)]
                public string XPath {
                    get { return _xpath; }
                    set { _xpath = value; }
                }

                [TaskAttribute("fragment", Required=true)]
                public string Fragment {
                    get { return _fragment; }
                    set { _fragment = value; }
                }

                #endregion Public Instance Properties

                #region Override implementation of Task
                protected override void ExecuteTask() {
                    System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                    document.Load(_filename);
                    System.Xml.XPath.XPathNavigator navigator = document.CreateNavigator();
                    navigator.SelectSingleNode(_xpath).AppendChild(_fragment);
                    document.Save(_filename);
                }
                #endregion Override implementation of Task
              }
            ]]>
        </code>
    </script>
Christopher Stott