Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting XML using a selected Xpath and a for loop

I currently have the following code:

XPathNodeIterator theNodes = theNav.Select(theXPath.ToString());

while (theNodes.MoveNext())
{
    //some attempts i though were close
    //theNodes.RemoveChild(theNodes.Current.OuterXml);
    //theNodes.Current.DeleteSelf();
}

I have set xpath to what I want to return in xml and I want to delete everything that is looped. I have tried a few ways of deleting the information but it does't like my syntax. I found an example on Microsoft support: http://support.microsoft.com/kb/317666 but I would like to use this while instead of a for each.

Any comments or questions are appreciated.

like image 682
Johnston Avatar asked Jun 28 '11 02:06

Johnston


3 Answers

Why not to use XDocument?

var xmlText = "<Elements><Element1 /><Element2 /></Elements>";
var document = XDocument.Parse(xmlText);

var element = document.XPathSelectElement("Elements/Element1");
element.Remove();

var result = document.ToString();

result will be <Elements><Element2 /></Elements>.

Or:

var document = XDocument.Load(fileName);

var element = document.XPathSelectElement("Elements/Element1");
element.Remove();

document.Savel(fileName);

[Edit] For .NET 2, you can use XmlDocument:

XmlDocument document = new XmlDocument();
document.Load(fileName);

XmlNode node = document.SelectSingleNode("Elements/Element1");
node.ParentNode.RemoveChild(node);

document.Save(fileName);

[EDIT]

If you need to remove all child elements and attributes:

XmlNode node = document.SelectSingleNode("Elements");
node.RemoveAll();

If you need to keep attributes, but delete elements:

XmlNode node = document.SelectSingleNode("Elements");
foreach (XmlNode childNode in node.ChildNodes)
    node.RemoveChild(childNode);
like image 181
Alex Aza Avatar answered Nov 07 '22 20:11

Alex Aza


string nodeXPath = "your x path";

XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);

XmlNode node = document.SelectSingleNode(nodeXPath);
node.RemoveAll();

XmlNode parentnode = node.ParentNode;
parentnode.RemoveChild(node);
document.Save("File Path");
like image 45
Bibhu Avatar answered Nov 07 '22 22:11

Bibhu


You can use XmlDocument:

string nodeXPath = "your x path";

XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);//or document.LoadXml(...

XmlNode node = document.SelectSingleNode(nodeXPath);

if (node.HasChildNodes)
{
    //note that you can use node.RemoveAll(); it will remove all child nodes, but it will also remove all node' attributes.

    for (int childNodeIndex = 0; childNodeIndex < node.ChildNodes.Count; childNodeIndex++)
    {
        node.RemoveChild(node.ChildNodes[childNodeIndex]);
    }
}

document.Save("your file path"));
like image 37
Jalal Said Avatar answered Nov 07 '22 20:11

Jalal Said