System.Xml.XmlResolver
The XmlResolver
class resolves external XML resources named by a Uniform Resource Identifier (URI). It is used by the XML parser to access external DTDs, schemas, and other resources.
On this page
Syntax
public abstract class XmlResolver
Inheritance
Object
→ XmlResolver
Properties
Name | Type | Description |
---|---|---|
Credentials | ICredentials | Gets or sets the credentials used to authenticate Web requests. |
Resolver | XmlResolver | Gets the current resolver (used in advanced scenarios). |
Methods
Name | Signature | Description |
---|---|---|
GetEntity | public abstract object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) | Returns the resource identified by the specified Uri . |
ResolveUri | public virtual Uri ResolveUri(Uri baseUri, string relativeUri) | Combines a base URI and a relative URI into a new absolute URI. |
GetEntityAsync | public virtual Task<object> GetEntityAsync(Uri absoluteUri, string role, Type ofObjectToReturn, CancellationToken cancellationToken) | Asynchronously returns the resource identified by the specified Uri . |
Remarks
The XmlResolver
class is an extensibility point. By default, XmlUrlResolver
is used, which supports HTTP, HTTPS, FILE, and other schemes. For secure environments, consider using a custom resolver that restricts the set of permissible URIs.
Examples
Creating a custom resolver that only allows local files:
using System;
using System.IO;
using System.Net;
using System.Xml;
public class LocalFileResolver : XmlResolver
{
public override ICredentials Credentials { set { } }
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
if (absoluteUri.IsFile)
{
return File.OpenRead(absoluteUri.LocalPath);
}
throw new NotSupportedException("Only local file URIs are allowed.");
}
}
// Usage
var settings = new XmlReaderSettings
{
XmlResolver = new LocalFileResolver()
};
using var reader = XmlReader.Create("example.xml", settings);
For async resolution:
public class AsyncWebResolver : XmlResolver
{
public override ICredentials Credentials { get; set; }
public override async Task<object> GetEntityAsync(Uri absoluteUri, string role, Type ofObjectToReturn, CancellationToken cancellationToken)
{
using var client = new HttpClient();
var stream = await client.GetStreamAsync(absoluteUri, cancellationToken);
return stream;
}
}