![](/img/trans.png)
[英]How to find invalid XML node in XDocument that is validated against a schema (XmlSchemaValidationException.SourceObject is null)
[英]How to resolve System.Xml.Schema.XmlSchemaValidationException
我正在嘗試使用在線 XSD 驗證 XML。這是我 controller 的當前代碼:
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using Microsoft.AspNetCore.Mvc;
namespace EINV.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class XmlController : Controller
{
[HttpPost]
public IActionResult ValidateXml2(IFormFile xmlFile, string xsdUrl)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlXsdResolver(); // Need this for resolving include and import
settings.ValidationType = ValidationType.Schema; // This might not be needed, I am using same settings to validate the input xml
//settings.DtdProcessing = DtdProcessing.Parse; // I have an include that is dtd. maybe I should prohibit dtd after I compile the xsd files.
settings.Schemas.Add(null, xsdUrl); // https://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd
settings.Schemas.Compile();
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xmlFile.OpenReadStream(), settings, "https://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/");
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
// the following call to Validate succeeds.
document.Validate(eventHandler);
// Load the XML file into an XmlDocument
return Ok();
}
protected class XmlXsdResolver : XmlUrlResolver
{
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
}
private void ValidationEventHandler(object? sender, ValidationEventArgs? e)
{
if (e?.Severity == XmlSeverityType.Error)
{
throw new Exception("XML validation error: " + e.Message);
}
}
}
}
在嘗試解決此問題時,我參考了其他幾篇文章,例如:
當所有 my.XSD 都存儲為資源時,如何解析 an.XSD 的 schemaLocation 屬性?
編譯兩個嵌入式 XSD:錯誤“無法解析‘schemaLocation’屬性
但總是以同樣的錯誤結束:
System.Xml.Schema.XmlSchemaValidationException: 'The 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2:UBLExtensions' element is not declared.'
我正在使用的 XML 位於此處: https://docs.oasis-open.org/ubl/os-UBL-2.1/xml/UBL -Invoice-2.1-Example.xml
我正在使用的 XSD 位於: https://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd
我認為你需要設置settings.Schemas.XmlResolver = new XmlUrlResolver();
同樣,作為標志settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
前。
這可能會讓你走得更遠,因為我認為有些模式(例如簽名)已導入但未找到。 所以最后你需要確保你有這些模式的本地副本,並讓你的解析器使用本地副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.