How to Filter and Select Nodes using an XPath Expression in C# .NET Framework

Cloudmersive
2 min readFeb 29, 2024

--

XPath is extremely useful for retrieving and processing important elements from XML files. With a free API, we can easily make XPath queries against any XML file in our system.

Using the below code, we can submit a valid XML XPath query expression in a free API request alongside an XML file and retrieve all matching XML nodes. To authorize our request, we’ll just need a free API key, and that will allow us to make up to 800 API calls per month with no commitments.

To structure our API call, let’s start by installing the SDK. Let’s run the below command in our Package Manager console to install via NuGet:

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

Next, let’s copy the below code to call the function, and let’s supply our API key and XML file path in the indicated snippets:

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 ConvertDataXmlFilterWithXPathExample
{
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
{
// Filter, select XML nodes using XPath expression, get results
XmlFilterWithXPathResult result = apiInstance.ConvertDataXmlFilterWithXPath(xPathExpression, inputFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataXmlFilterWithXPath: " + e.Message );
}
}
}
}

When we make our request, we’ll receive a response object following the below JSON example:

{
"Successful": true,
"XmlNodes": [
"string"
],
"ResultCount": 0
}

That’s all there is to it — no more code required!

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet