CodexBloom - Programming Q&A Platform

implementing XML Validation Against XSD in .NET - Schema Not Matching

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
xml validation xsd .net-core csharp

I'm confused about I've encountered a strange issue with I'm working on a project and hit a roadblock. I've been banging my head against this for hours. I'm working on a .NET Core application (version 3.1) where I'm trying to validate an XML document against an XSD schema. Despite following the steps outlined in the Microsoft documentation, my XML does not seem to match the schema, and I'm receiving the behavior: 'The element 'Root' in namespace 'http://example.com/schema' has invalid child element 'Child' in namespace 'http://example.com/schema'.' Here's the XML file I'm trying to validate: ```xml <?xml version="1.0" encoding="UTF-8"?> <Root xmlns="http://example.com/schema"> <Child>Some Value</Child> </Root> ``` And here’s the corresponding XSD schema: ```xml <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/schema" xmlns="http://example.com/schema" elementFormDefault="qualified"> <xs:element name="Root"> <xs:complexType> <xs:sequence> <xs:element name="Child" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ``` To validate the XML, I'm using the following C# code: ```csharp using System; using System.Xml; using System.Xml.Schema; class Program { static void Main() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("path/to/your.xml"); XmlSchemaSet schema = new XmlSchemaSet(); schema.Add("http://example.com/schema", "path/to/your.xsd"); xmlDoc.Schemas.Add(schema); xmlDoc.Validate((sender, e) => { Console.WriteLine(e.Message); }); } } ``` I've double-checked the namespace in both the XML and the XSD, and they seem to be correct. However, I still receive the mentioned validation behavior. I've also tried moving the `xmlns` attribute into the `Root` element only, but the behavior continues. Can anyone help identify what might be wrong, or any potential best practices for XML validation in .NET Core? This is part of a larger API I'm building. This is part of a larger service I'm building. This is my first time working with Csharp 3.11. Hoping someone can shed some light on this. For reference, this is a production desktop app. Any examples would be super helpful.