How to Replace XML Nodes with New Code in C# .NET Framework

Cloudmersive
2 min readFeb 29, 2024

--

Programmatically changing the content of an XML file can be an arduous task. Thankfully, with the help of a free API, we won’t have to write any new code ourselves.

By copying and pasting complementary code examples provided below, we can take advantage of a free API that allow us to replace XML nodes (selected via XPath expression) in an XML file with entirely new code. Once we’re done structuring our API call, the entire find + replace operation will take seconds.

Before we get started, we’ll just need to acquire a free API key to authorize our API requests. These allow a limit of 800 API calls per month with no commitments (once we reach our limit, the total will automatically reset the following month).

With our API key copied to our clipboard, we can start structuring our API call by running the below command in our Package Manager console. This installs the SDK via NuGet:

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

After that, we can copy the below ready-to-run code examples into our file to call the function. Once we copy our API key into the authorization snippet, we can provide our file path, XPath expression and XML Node replacement values 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 ConvertDataXmlEditReplaceWithXPathExample
{
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
var xmlNodeReplacement = xmlNodeReplacement_example; // string | XML Node replacement content

try
{
// Replaces XML nodes matching XPath expression with new node
XmlReplaceWithXPathResult result = apiInstance.ConvertDataXmlEditReplaceWithXPath(inputFile, xPathExpression, xmlNodeReplacement);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlEditReplaceWithXPath: " + e.Message );
}
}
}
}

That’s all there is to it — our API call will return our resulting XML document with all selected nodes replaced by new values.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet