#region CPL License
/*
Nuclex.NAnt.Tasks
Copyright (C) 2009 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Win32;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;
using System.Xml;
namespace Nuclex.NAnt.Tasks {
/// Removes nodes from XML documents
[TaskName("xmlremove")]
public class XmlRemoveTask : Task {
/// Initializes a new XML node removal task
public XmlRemoveTask() { }
/// XPath of the nodes that will be removed from an XML file
[TaskAttribute("xpath", Required = true), StringValidator(AllowEmpty = false)]
public string XPath {
get { return this.xPath; }
set { this.xPath = value; }
}
/// XML file from which nodes will be removed
[TaskAttribute("file", Required = true)]
public FileInfo File {
get { return this.xmlFile; }
set { this.xmlFile = value; }
}
/// Executes the task
protected override void ExecuteTask() {
XmlDocument document = new XmlDocument();
document.Load(this.xmlFile.FullName);
int count = 0;
foreach(XmlNode node in document.SelectNodes(this.xPath)) {
node.ParentNode.RemoveChild(node);
++count;
}
// If the user wants the task to fail if no nodes matched his XPath, do so now.
if(count == 0) {
if(FailOnError) {
throw new BuildException(String.Format("Node not found by XPath '{0}'", XPath));
}
}
document.Save(this.xmlFile.FullName);
Log(Level.Info, "Removed {0} XML nodes from {1}", count, this.xmlFile.FullName);
}
/// File to remove nodes from
private FileInfo xmlFile;
/// XPath for the nodes to be removed
private string xPath;
}
} // namespace Nuclex.NAnt.Tasks