Search code examples
c#xmlxsddefault

C# XmlDocument is not being updated with respective XSD default attributes


Here is an example from a xsd and a xml

XML

<?xml version="1.0" encoding="UTF-8"?>
<config test2="true">
</config>

XSD

<?xml version="1.0" encoding="utf-8"?>   
<xs:schema  targetNamespace="rules.xsd" xmlns="rules.xsd" elementFormDefault="qualified"  xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
  <xs:element name="config">
    <xs:complexType>
      <xs:attribute name="test1" type="xs:boolean" default="false" />
      <xs:attribute name="test2" type="xs:string" default="mary123" />
    </xs:complexType>
  </xs:element>
</xs:schema>

I can use this xsd to validate this xml in C# using this block of code

XmlDocument doc = new XmlDocument();
XmlTextReader schemaReader = new XmlTextReader(System.IO.Path.GetFullPath("Mi_XSD_here.xsd"));
XmlSchema schema = XmlSchema.Read(schemaReader, ValidationCallBack);
doc.Schemas.Add(schema);
doc.Load("Mi_XML_here.xml");
doc.Validate(ValidationCallBack);

The problem is: I have two default attributes in xsd, but when i run this code he doesn't insert the attributes in XmlDocument, the result is the same xml that i passed to the system.

The default attributes are not working and i cant figure why they aren't working, i do believe that exists other forms to solve this problem, i did find this but didn't worked

Extensions.Validate Method

obs: ValidationCallBack is some return on error function that i think isn't related to the problems


Solution

  • Your schema's target namespace is rules.xsd so your xml file needs to include that to validate against the schema. Also I'm assuming teste2 is a typo (since that doesn't conform to the schema) and you meant test2:

    <config test2="" xmlns="rules.xsd" />
    

    In this case only test1 will get added with a default since test2 is already set to an empty string.