How to Set the Value Contents of XML Nodes Matching an XPath Expressing in C# .NET Framework
Writing C# code to process XML files can be a little challenging. Thankfully, we don’t need to write our own code to make complex changes to XML files.
Using the ready-to-run code examples below, we can take advantage of a free API that allows us to make an XPath query against an XML file in our system and subsequently set a new XML value in the matching nodes. This takes care of a multi-step process in one quick operation with minimal code.
To authorize our API calls for free, we’ll just need a free API key. These allow a limit of 800 API calls per month with no commitments (our total simply resets the following month once we reach it).
To structure our API call in C# .NET framework, let’s begin by installing the SDK. To install via NuGet, let’s run the following command in our Package Manager console:
Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2
Next, let’s copy the below code examples into our file to call the function. We can include our API key in the indicated configuration snippet, and then we can supply our file path, XPath query string and XML value string as 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 ConvertDataXmlEditSetValueWithXPathExample
{
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 xmlValue = xmlValue_example; // string | XML Value to set into the matching XML nodes
try
{
// Sets the value contents of XML nodes matching XPath expression
XmlSetValueWithXPathResult result = apiInstance.ConvertDataXmlEditSetValueWithXPath(inputFile, xPathExpression, xmlValue);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlEditSetValueWithXPath: " + e.Message );
}
}
}
}
Our API response will contain the resulting XML document as a string with all matching nodes changed.