Skip to content

Search EricksonLopez.* Ecosystem

Type a library name, NuGet package ID, .NET type, or architectural concept to search across the portal.

Getting Started with EricksonLopez.Xml.Validation

Install EricksonLopez.Xml.Validation (1.0.0 on NuGet). Note that there is no separate root EricksonLopez.Xml NuGet package.

dotnet add package EricksonLopez.Xml.Validation --version 1.0.0

Register schemas into XmlSchemaCache, validate with XmlSchemaValidator, and wire singleton IXmlSchemaCache + IXmlSchemaValidator via AddXmlValidation:

using System;
using EricksonLopez.Result;
using EricksonLopez.Xml.Validation;
using Microsoft.Extensions.DependencyInjection;
namespace Example.XmlQuickStart;
public static class XmlUsage
{
public static void ValidateAndRegister()
{
const string ns = "https://example.com/orders";
const string xsd = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/orders"
elementFormDefault="qualified">
<xs:element name="Order">
<xs:complexType>
<xs:sequence>
<xs:element name="Id" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
""";
const string xml = """
<Order xmlns="https://example.com/orders">
<Id>ORD-100</Id>
</Order>
""";
var cache = new XmlSchemaCache();
cache.RegisterSchema(ns, xsd);
var validator = new XmlSchemaValidator(cache);
Result<bool> result = validator.Validate(xml, ns);
if (result.IsFailure || !result.Value)
{
throw new InvalidOperationException("Expected valid XML document.");
}
var services = new ServiceCollection();
services.AddLogging();
services.AddXmlValidation(options =>
{
options.IncludeWarnings = true;
options.MaxCharactersInDocument = 10_000_000;
});
using var provider = services.BuildServiceProvider(
new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true });
var diValidator = provider.GetRequiredService<IXmlSchemaValidator>();
if (diValidator is null)
{
throw new InvalidOperationException("IXmlSchemaValidator was not resolved.");
}
}
}