How to Remove XML Nodes via XPath Expression in C# .NET Framework
Removing nodes or items from an XML file is a good way to reduce file size — or we may just want to clean up unnecessary or outdated information.
With complementary code examples provided below, we can programmatically remove nodes or items from our XML files with a free API. In our API request, we’ll need to provide our XML file path along with a valid XPath expression, and we’ll get an updated XML file in our response.
To authorize our request, we’ll need a free API key. This will allow a limit of 800 API calls per month with no additional commitments (our call total will reset the following month once we reach it).
We can begin structuring our API call by installing 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 can copy the below code into our file to call the function. Let’s copy our API key into the authorization snippet, and then let’s supply our file path & XPath expression in their respective variables:
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 ConvertDataXmlRemoveWithXPathExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ConvertDataApi();
var xPathExpression = xPathExpression_example; // string | Valid XML XPath query expression
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.
try
{
// Remove, delete XML nodes and items matching XPath expression
XmlRemoveWithXPathResult result = apiInstance.ConvertDataXmlRemoveWithXPath(xPathExpression, inputFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlRemoveWithXPath: " + e.Message );
}
}
}
}
Now we can easily make important changes to XML files with minimal code.