How to Delete XML Child Elements using C# .NET Framework

Cloudmersive
2 min readMar 4, 2024

--

Using complementary code examples, we can easily take advantage of a free API to remove specific child elements from an XML file without impacting the parent node whatsoever.

Our request variables will include our XML file path along with a valid XPath expression to identify the child elements we’re targeting.

To structure our API call, we’ll first need to install the SDK. We can run the below command in our Package Manager console to install via NuGet:

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2

Next, we’ll need to turn our attention to authorization. We can make free API calls with a free API key (specifically, this will allow a limit of 800 API calls per month with no additional commitments).

Finally, we can call our function. Let’s copy the below code into our file, supply our API key in the authorization snippet, and then configure our request variables with our XML file and XPath expression:

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;

namespace Example
{
public class ConvertDataXmlEditRemoveAllChildNodesWithXPathExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");

var apiInstance = new ConvertDataApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input XML file to perform the operation on.
var xPathExpression = xPathExpression_example; // string | Valid XML XPath query expression

try
{
// Removes, deletes all children of nodes matching XPath expression, but does not remove the nodes
XmlRemoveAllChildrenWithXPathResult result = apiInstance.ConvertDataXmlEditRemoveAllChildNodesWithXPath(inputFile, xPathExpression);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlEditRemoveAllChildNodesWithXPath: " + e.Message );
}
}
}
}

Now we can easily make programmatic changes to our XML file child elements without worrying about impacting parent nodes.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet