How to Add a Child to an XML Node in C# .NET Framework
Writing code to nest child elements in XML nodes can be a little tricky.
Thankfully, using the ready-to-run C# code examples provided below, we don’t have to write any new code to programmatically edit our XML files. We can call a free API instead, locating our target XML node with an XPath expression and filling that node with child elements of our choosing — all in one simple request.
To structure our API call, let’s begin by installing the SDK. We can run this command in our Package Manager console to install via NuGet:
Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2
Next, let’s turn our attention to API authorization. We’ll just need a free API key to make our API call; this will allow a limit of 800 API calls per month (our total will reset the following month if we reach our limit).
With our API key ready, let’s now copy the below code into our file to call the function, and then let’s supply our XML file, XPath expression and XML child nodes in our request 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 ConvertDataXmlEditAddChildWithXPathExample
{
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 xmlNodeToAdd = xmlNodeToAdd_example; // string | XML Node to add as a child
try
{
// Adds an XML node as a child to XML nodes matching XPath expression
XmlAddChildWithXPathResult result = apiInstance.ConvertDataXmlEditAddChildWithXPath(inputFile, xPathExpression, xmlNodeToAdd);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlEditAddChildWithXPath: " + e.Message );
}
}
}
}
Just like that, we can easily build out XML nodes programmatically with minimal code.