Add attribute to an xml node with nant
Asked Answered
P

2

5

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.

Pique answered 11/12, 2008 at 10:49 Comment(0)
F
4

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.

Flavouring answered 15/1, 2009 at 5:19 Comment(0)
P
3

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>
Panicle answered 20/10, 2010 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.