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

给出以下xml:
<rootnode>
   <childnode arg="a">Content A</childnode>
   <childnode arg="b">Content A</childnode>
</rootnode>
将XMLPoke与以下XPath一起使用:
rootnode/childnode[arg='b']
结果(如果替换字符串为空)是:
<rootnode>
   <childnode arg="a">Content A</childnode>
   <childnode arg="b"></childnode>
</rootnode>
当我们真正想要移除子节点本身时,已删除了childnode的内容。期望的结果是:
<rootnode>
   <childnode arg="a">Content A</childnode>
</rootnode>
必须根据childnode参数选择子节点。     
已邀请:
我举起手来!这是一个提出错误问题的经典案例。 问题是您无法使用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 );
        }
    }
}
将上述内容与对NAnt.exe.config文件的修改结合起来,以在构建文件中加载自定义目标和以下脚本:
<xmlstrip xpath="//rootnode/childnode[@arg = 'b']" file="target.xml" />
这将从target.xml中删除带有值为b的参数arg的子节点。这首先是我真正想要的!     

要回复问题请先登录注册