如何使用Nant的xmlpoke目标删除节点

Iai*_*ain 15 xml nant xmlpoke

给出以下xml:

<rootnode>
   <childnode arg="a">Content A</childnode>
   <childnode arg="b">Content A</childnode>
</rootnode>
Run Code Online (Sandbox Code Playgroud)

XMLPoke与以下XPath一起使用:

rootnode/childnode[arg='b']
Run Code Online (Sandbox Code Playgroud)

结果(如果替换字符串为空)是:

<rootnode>
   <childnode arg="a">Content A</childnode>
   <childnode arg="b"></childnode>
</rootnode>
Run Code Online (Sandbox Code Playgroud)

当我们真正想要移除childnode本身时,已删除了childnode的内容.期望的结果是:

<rootnode>
   <childnode arg="a">Content A</childnode>
</rootnode>
Run Code Online (Sandbox Code Playgroud)

必须根据childnode参数选择子节点.

Iai*_*ain 25

我举起手来!这是一个提出错误问题的经典案例.

问题是您无法使用xmlpoke删除单个节点.Xmlpoke只能用于编辑特定节点或属性的内容.根据仅使用标准Nant目标的问题,没有一种优雅的方法来删除子节点.它可以使用Nant中的属性使用一些不优雅的字符串操作来完成,但是你为什么要这样做?

最好的方法是编写一个简单的Nant目标.这是我之前准备的一个:

using System;
using System.IO;
using System.Xml;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace XmlStrip
{
    [TaskName("xmlstrip")]
    public class XmlStrip : Task
    {
        [TaskAttribute("xpath", Required = true), StringValidator(AllowEmpty = false)]
        public string XPath { get; set; }

        [TaskAttribute("file", Required = true)]
        public FileInfo XmlFile { get; set; }

        protected override void ExecuteTask()
        {
            string filename = XmlFile.FullName;
            Log(Level.Info, "Attempting to load XML document in file '{0}'.", filename );
            XmlDocument document = new XmlDocument();
            document.Load(filename);
            Log(Level.Info, "XML document in file '{0}' loaded successfully.", filename );

            XmlNode node = document.SelectSingleNode(XPath);
            if(null == node)
            {
                throw new BuildException(String.Format("Node not found by XPath '{0}'", XPath));
            }

            node.ParentNode.RemoveChild(node);

            Log(Level.Info, "Attempting to save XML document to '{0}'.", filename );
            document.Save(filename);
            Log(Level.Info, "XML document successfully saved to '{0}'.", filename );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将上述内容与对NAnt.exe.config文件的修改结合起来,以在构建文件中加载自定义目标和以下脚本:

<xmlstrip xpath="//rootnode/childnode[@arg = 'b']" file="target.xml" />
Run Code Online (Sandbox Code Playgroud)

这将删除childnode与参数ARG与值btarget.xml.这首先是我真正想要的!