如何使用Nant的xmlpoke目标删除一个节点
发布时间:2020-12-16 07:52:35 所属栏目:百科 来源:网络整理
导读:给定以下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 child
给定以下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> 当我们实际想要删除子节点时,子节点的内容已被删除.期望的结果是: <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的子节点.我真正想要的是什么? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |