I am building a web service in .NET that will pass data back and forth via XML. I would like to validate the XML in the incoming requests using an XSD that I have defined.
Here is the XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="POSearch">
<xs:sequence minOccurs="0" maxOccurs="10">
<xs:element name="POID" type="xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Here is the XML:
<POSearch>
<POID>1</POID>
<POID>2</POID>
</POSearch>
Here is the validation code in C#:
static void Main(string[] args){
XmlSchemaSet iSchemas = new XmlSchemaSet();
iSchemas.Add(string.Empty, #"...xsd file location");
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(iSchemas);
XmlReader reader = XmlReader.Create(#"...xml file location", settings);
try {
while(reader.Read())
;
}
catch(Exception ex) {
Console.WriteLine(ex.Message);
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs args) {
if(args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
I feel like I had this working before and I'm not completely sure why this isn't working now. Whenever I run this I get the following Exception Message:
Validation error: The 'POSearch' element is not declared.
Have I defined my XSD wrong? Is my validation code wrong? The elements are all clearly there. Any help pointing me in the right direction is greatly appreciated.
You have the type declared but no element declared of that type.
Add an element declaration:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="POSearch" type="POSearch"/>
<xs:complexType name="POSearch">
<xs:sequence minOccurs="0" maxOccurs="10">
<xs:element name="POID" type="xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Try this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="POSearch">
<xs:sequence minOccurs="0" maxOccurs="10">
<xs:element name="POID" type="xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
<xs:element name="POSearch" type="POSearch"/>
</xs:schema>
Related
I have an xml schema file that describes an element called MessageProcessingResult that can have child elements 'MessageID' and 'Category'. My xml clearly has these elements yet when I validate the xml against the schema I get an error stating the 'Category' element is invalid:
The element 'MessageProcessingResult' in namespace
'http://test.com/MessageProcessing' has invalid child element
'Category' in namespace 'http://test.com/MessageProcessing'. List of
possible elements expected: 'Category, MessageID'.
I must be defining my schema incorrectly, but I don't know exactly what it is.
My schema, xml and validation code are as follows:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://test.com/MessageProcessing"
targetNamespace="http://test.com/MessageProcessing"
elementFormDefault="unqualified"
attributeFormDefault="unqualified">
<xs:element name="MessageProcessingResult">
<xs:complexType>
<xs:all>
<xs:element name="MessageID" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:element name="Category">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Success"/>
<xs:enumeration value="Problem"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
xml that looks like this:
<MessageProcessingResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://test.com/MessageProcessing">
<Category>Success</Category>
<MessageID>id</MessageID>
</MessageProcessingResult>
I validate with this code:
public class XmlValidator
{
public void Validate(Stream strXml)
{
XmlReaderSettings settings = new XmlReaderSettings();
//settings.Schemas.Add(null, #"Schema\MessageProcessingResults.xsd");
settings.Schemas.Add(null, #"Schema\MessageProcessingResult.xsd");
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(XmlSchemaValidationEventHandler);
XmlReader xml = XmlReader.Create(strXml, settings);
this.Errors = new List<string>();
while (xml.Read()) { }
}
public List<string> Errors { get; set; }
private void XmlSchemaValidationEventHandler(object sender, ValidationEventArgs e)
{
this.Errors.Add($"{e.Severity} {e.Message}");
}
}
In your XSD, change
elementFormDefault="unqualified"
to
elementFormDefault="qualified"
Your explicit setting of elementFormDefault="unqualified" (which also happens to be the default setting) means that locally declared elements are in no namespace. This is undesired in your case (and rarely ever desired, in fact). For further details, see What does elementFormDefault do in XSD?
I am using Visual Studio 2015.
I apologize for the poorly named "firstName" element. It should have been "fullName", but since I already generated the class for the schema, and this is just for my own learning, I left it as is.
I have an XML schema here:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="address-schema"
targetNamespace="http://tempuri.org/address-schema.xsd"
elementFormDefault="qualified"
attributeFormDefault="qualified"
xmlns:addr="http://tempuri.org/address-schema.xsd"
xmlns:mstns="http://tempuri.org/address-schema.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="firstName">
<xs:complexType>
<xs:sequence>
<xs:element name="first" type="addr:nameComponent"/>
<xs:element name="middle" type="addr:nameComponent" minOccurs="0"/>
<xs:element name="last" type="addr:nameComponent"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="nameComponent">
<xs:simpleContent>
<xs:extension base="xs:string"/>
</xs:simpleContent>
</xs:complexType>
</xs:schema>
And an XML file that I think conforms to the schema:
<?xml version="1.0" encoding="utf-8" ?>
<addr:address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tempuri.org/address-schema.xsd address-schema.xsd"
xmlns:addr="http://tempuri.org/address-schema.xsd">
<addr:firstName>
<addr:first>Some</addr:first>
<addr:middle>Bodys</addr:middle>
<addr:last>Name</addr:last>
</addr:firstName>
</addr:address>
And the code that is attempting to validate the XML is here (note that the "address" class that the XML file is getting deserialized into is an auto generated class from xsd.exe):
address address;
var xmlSchemaSerializer = new XmlSerializer(typeof(XmlSchema));
var addressXmlSerializer = new XmlSerializer(typeof(address));
var schemas = new XmlSchemaSet();
XmlSchema schema;
using (var xsdStream = File.OpenRead("address-schema.xsd"))
{
schema = (XmlSchema)xmlSchemaSerializer.Deserialize(xsdStream);
}
schemas.Add(schema);
var settings = new XmlReaderSettings
{
Schemas = schemas,
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation
};
settings.ValidationEventHandler += (sender, arguments) =>
{
throw new XmlSchemaValidationException(arguments.Message);
};
using(Stream addressXmlStream = File.OpenRead("address-doc.xml"))
using (XmlReader reader = XmlReader.Create(addressXmlStream, settings))
{
address = (address)addressXmlSerializer.Deserialize(reader);
}
Console.WriteLine(address.firstName.first.Value == "Some" ? "Success!" : "Fail");
Console.ReadKey();
The exception ('System.Xml.Schema.XmlSchemaValidationException'The global element 'http://tempuri.org/address-schema.xsd:address' has already been declared.) is thrown in the ValidationEventHandler.
Any help or suggestions would be appreciated. Thanks in advance!
The cause of your exception is that your document has a schema location hint that loads the schema, but you've already loaded it.
Either don't pre-load the schema or remove the xsi:schemaLocation attribute from your document.
I have 2 xsd files content in a dictionary. I want to merge both the contents and create one xsd file.
1st xsd content from dictionary has a import tag pointing to 2nd xsd in the dictionary.
1st xsd -
<?xml version="1.0" encoding="IBM437"?>
<xs:schema xmlns:tns="http://schemas.microsoft.com/BizTalk/EDI/EDIFACT/2006/EnrichedMessageXML" targetNamespace="http://schemas.microsoft.com/BizTalk/EDI/EDIFACT/2006/Enr
ichedMessageXML" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import schemaLocation="COMP.EDI._00401._810.Schemas.Headers" namespace="http://EDI/Headers" />
<xs:element name="X12EnrichedMessage">
<xs:complexType>
<xs:sequence>
<xs:element xmlns:q1="http://EDI/Headers" ref="q1:Headers" />
<xs:element name="TransactionSet">
<xs:complexType>
<xs:sequence>
<xs:element xmlns:q2="http://schemas.microsoft.com/BizTalk/EDI/X12/2006" ref="q2:X12_00401_810" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
2nd sxd -
<?xml version="1.0" encoding="IBM437"?>
<xs:schema xmlns:b="http://schemas.microsoft.com/BizTalk/2003" xmlns="http://EDI/Headers" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://EDI/Headers">
<xs:element name="Headers">
// Some content here
</xs:element>
</xs:schema>
desired xsd I want is the merger of both the xsd documents.
I am following this : http://msdn.microsoft.com/en-us/library/ms256237%28v=vs.110%29.aspx article, I am able to add the schemas to schemaset object also, but when I am using RecurseExternals function (from the article) this is not showing the merged xsd but 2 different xsd.
my block of code -
XmlSchemaSet schemaSet = new XmlSchemaSet();
// This prevents schemaLocation and Namespace warnings
// at this point we already have the schema from schemaLocation.
//schemaSet.XmlResolver = null;
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
// add schema in schema set from schemacollection object
foreach (var item in schemaCollection)
{
schemaSet.Add(item.Key, new XmlTextReader(new StringReader(item.Value)));
}
schemaSet.Compile();
XmlSchema mainXmlSchema = null;
XmlSchemaImport import = new XmlSchemaImport();
foreach (XmlSchema sch in schemaSet.Schemas())
{
// pick the main schema from the schemaset to include
// other schemas in the collection.
if (sch.TargetNamespace == mainSchemaNS)
{
mainXmlSchema = sch;
}
else
{
import.Namespace = sch.TargetNamespace;
import.Schema = sch;
mainXmlSchema.Includes.Add(import);
}
}
schemaSet.Reprocess(mainXmlSchema);
schemaSet.Compile();
RecurseExternals(mainXmlSchema);
am I doing anything wrong ?
I'm trying to add the annotation element inside the xs:choice. According to the xs:choice syntax, this could be possible. I could not find the sample of choice with annotation inside BTW. My current version of xsd file contains an element:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://www.es.de/es3/flex/simple"
elementFormDefault="qualified"
xmlns="http://www.es.de/es3/flex/simple"
xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:flex="http://www.es.de/es3/flex/flexBase">
<xs:import namespace="http://www.es.de/es3/flex/flexBase" />
<xs:element name="ESS3754">
<xs:complexType>
<xs:choice>
<xs:annotation>
<xs:appinfo>
<flex:ControlHeadline>Headline_VVVVV</flex:ControlHeadline>
<flex:helpText>HelpText_VVVVV</flex:helpText>
</xs:appinfo>
</xs:annotation>
<xs:element name="String1" type="xs:string" minOccurs="1" maxOccurs="1"/>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
However, while parsing the xsd file, the Annotation of the object System.Xml.Schema.XmlSchemaChoice is always null.
The code part:
public List<FSBaseItem> Parse( XmlTextReader xsdReader )
{
try
{
// prepare schema set for schema validation and raw template xsd "enrichment"
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += ValidationCallbackOne;
// include base schema
XmlSchema baseXsd = FlexXmlSchemaReader.ReadBase();
schemaSet.Add( baseXsd );
// The Read method will throw errors encountered on parsing the schema
XmlSchema xsd = XmlSchema.Read( xsdReader, ValidationCallbackOne );
schemaSet.Add( xsd );
// The Compile method will throw errors encountered on compiling the schema
schemaSet.Compile();
// create root
FSElement rootElement = new FSElement( this.GetNewId() );
// traverse body
this.TraverseSOM( xsd, rootElement );
// validate
this.ValidateFSItems( rootElement.Items );
// init lists containers with minimum elements
InitEmptyFEListItems( rootElement );
return rootElement.Items;
}
finally
{
xsdReader.Close();
}
}
Already in the beginning the choice element annotation is null. Could somebody give some working sample or add some hints?
Annotations certainly can be put inside xs:choice. Look at the following xsd taken from Inline Annotated Schema
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:version="1.0" jaxb:extensionBindingPrefixes="xjc">
<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings>
<xjc:superClass name="com.syh.Shape"/>
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>
<xs:element name="Widgets">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:appinfo>
<jaxb:property name="Shapes"/>
</xs:appinfo>
</xs:annotation>
<xs:element name="Rectangle" type="Rectangle"/>
<xs:element name="Square" type="Square"/>
<xs:element name="Circle" type="Circle"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:complexType name="Rectangle">
<xs:sequence>
<xs:element name="Width" type="xs:integer"/>
<xs:element name="Height" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Square">
<xs:sequence>
<xs:element name="Length" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Circle">
<xs:sequence>
<xs:element name="Radius" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Adapting similar strategy to your xsd yields something like the following:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://www.es.de/es3/flex/simple"
elementFormDefault="qualified"
xmlns="http://www.es.de/es3/flex/simple"
xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:flex="http://www.es.de/es3/flex/flexBase">
<xs:import namespace="http://www.es.de/es3/flex/flexBase" />
<xs:element name="ESS3754">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:appinfo>
<flex:ControlHeadline>Headline_VVVVV</flex:ControlHeadline>
<flex:helpText>HelpText_VVVVV</flex:helpText>
</xs:appinfo>
</xs:annotation>
<xs:element name="String1" type="xs:string" minOccurs="1" maxOccurs="10"/>
<xs:element name="NewlyAdded" type="Coordinate" minOccurs="1" maxOccurs="10"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:complexType name="Coordinate">
<xs:sequence>
<xs:element name="LocationX" type="xs:integer"/>
<xs:element name="LocationY" type="xs:integer"/>
<xs:element name="LocationZ" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
and the xsd is perfectly valid and looks like the following in Visual Studio [XSD] Desginer:
Update 1
I agree on the fact that debugger shows item annotation as null [I could not find it either but I should] and it is quite frustrating. I reconstructed the document using the code and you can annotate your element using the following workaround:
Consider the following XSD which does not have any XmlSchemaChoice and is saved as stack-problem2.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://www.es.de/es3/flex/simple"
elementFormDefault="qualified"
xmlns="http://www.es.de/es3/flex/simple"
xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:flex="http://www.es.de/es3/flex/flexBase">
<xs:import namespace="http://www.es.de/es3/flex/flexBase" />
<xs:complexType name="Coordinate">
<xs:sequence>
<xs:element name="LocationX" type="xs:integer"/>
<xs:element name="LocationY" type="xs:integer"/>
<xs:element name="LocationZ" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Now you can load this into memory and add annotations programmatically to the XmlSchemaChoice element:
public void Parse()
{
try
{
XmlTextReader reader2 = new XmlTextReader(#"stack-problem2.xsd");
XmlSchema myschema2 = XmlSchema.Read(reader2, ValidationCallback);
var simpleAnotation = new XmlSchemaAnnotation();
simpleAnotation.Id = "Lost Anotation";
// <xs:complexType name="ESS3754">
XmlSchemaComplexType complexType = new XmlSchemaComplexType();
myschema2.Items.Add(complexType);
complexType.Name = "ESS3754";
// <xs:choice minOccurs="1" maxOccurs="1">
XmlSchemaChoice choice = new XmlSchemaChoice();
complexType.Particle = choice;
choice.MinOccurs = 1;
choice.MaxOccurs = 1;
XmlSchemaElement elementSelected = new XmlSchemaElement();
choice.Items.Add(elementSelected);
elementSelected.Name = "String1";
AnnonateMyComplexType(choice);
FileStream file = new FileStream(#"satck-solution.xsd", FileMode.Create, FileAccess.ReadWrite);
XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding());
xwriter.Formatting = Formatting.Indented;
myschema2.Write(xwriter);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static void AnnonateMyComplexType(XmlSchemaChoice xmlSchemaComplexType)
{
XmlSchemaAnnotation myCustomAnnotation = new XmlSchemaAnnotation();
xmlSchemaComplexType.Annotation = myCustomAnnotation;
// <xs:documentation>State Name</xs:documentation>
XmlSchemaDocumentation schemaDocumentation = new XmlSchemaDocumentation();
myCustomAnnotation.Items.Add(schemaDocumentation);
schemaDocumentation.Markup = TextToNodeArray("Headline_VVVVV");
// <xs:appInfo>Application Information</xs:appInfo>
XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo();
myCustomAnnotation.Items.Add(appInfo);
appInfo.Markup = TextToNodeArray("Headline_VVVVV");
}
static void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.Write("WARNING: ");
else if (args.Severity == XmlSeverityType.Error)
Console.Write("ERROR: ");
Console.WriteLine(args.Message);
}
Running above will return the following XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns="http://www.es.de/es3/flex/simple" xmlns:flex="http://www.es.de/es3/flex/flexBase" xmlns:mstns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" targetNamespace="http://www.es.de/es3/flex/simple" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import namespace="http://www.es.de/es3/flex/flexBase" />
<xs:complexType name="Coordinate">
<xs:sequence>
<xs:element name="LocationX" type="xs:integer" />
<xs:element name="LocationY" type="xs:integer" />
<xs:element name="LocationZ" type="xs:integer" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ESS3754">
<xs:choice minOccurs="1" maxOccurs="1">
<xs:annotation>
<xs:documentation>Headline_VVVVV</xs:documentation>
<xs:appinfo>Headline_VVVVV</xs:appinfo>
</xs:annotation>
<xs:element name="String1" />
</xs:choice>
</xs:complexType>
</xs:schema>
So to answer your first question: Yes, Annotation can be definitely put inside XmlSchemaChoice elements (Both through code and directly) [Not necessarily outside xmlSchemaChoice as the top element based on your experiment] and to address your second problem: [I had similar experience as of yours! It shows the annotation as null although it is not]
For anyone else running into this issue, I have found by reflecting the classes of the System.Xml.Schema namespace that, upon compiling a schemaset, the annotations of elements are copied to their children.
So Vytas999 should be able (as I have been able) to find his missing annotation by inspecting the XmlSchemaParticle objects in the XmlSchemaChoice.Items property.
I ran into the same problem - I needed to process an XSD provided by external entity and the Annotation of XmlSchemaChoice was always null.
Elaborating on #Adrian's answers the code I successfully use is below. In my case I traverse the schema from the root down, when I hit XmlSchemaSequence I itereate over its Items collection:
var index = 0;
foreach (var childObject in sequence.Items)
{
ExtractElement(childObject, index);
++index ;
}
When childObject is of type XmlSchemaChoice (assuming it is in variable xmlSchemaChoice, then instead of
// DOES NOT WORK - always null
var choiceAnnotation = xmlSchemaChoice.Annotation
I access the Annotation like this:
((xmlSchemaChoice.Parent as XmlSchemaSequence)?.Items[index] as XmlSchemaChoice)?.Annotation
Would you expect the same result? Well, it is not..
This code is just sample snippet describing accessing the Annotation via Parent's Items, it is NOT general purpose code and might need some adaptation to your exact case.
Here is my first attempt at validating XML with XSD.
The XML file to be validated:
<?xml version="1.0" encoding="utf-8" ?>
<config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">
<levelVariant>
<filePath>SampleVariant</filePath>
</levelVariant>
<levelVariant>
<filePath>LegendaryMode</filePath>
</levelVariant>
<levelVariant>
<filePath>AmazingMode</filePath>
</levelVariant>
</config>
The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="config">
<xs:complexType>
<xs:sequence>
<xs:element name="levelVariant">
<xs:complexType>
<xs:sequence>
<xs:element name="filePath" type="xs:anyURI">
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists?
The validation code in C#:
public void SetURI(string uri)
{
XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml");
// begin confusion
// exception here
string schemaURI = toValidate.Attributes("xmlns").First().ToString()
+ toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, schemaURI);
XDocument toValidateDoc = new XDocument(toValidate);
toValidateDoc.Validate(schemas, null);
// end confusion
root = toValidate;
}
Running the above code gives this exception:
The ':' character, hexadecimal value 0x3A, cannot be included in a name.
Any illumination would be appreciated.
Rather than using the XDocument.Validate extension method, I would use an XmlReader which can be configured to process an inline schema via XmlReaderSettings. You could do some thing like the following code.
public void VerifyXmlFile(string path)
{
// configure the xmlreader validation to use inline schema.
XmlReaderSettings config = new XmlReaderSettings();
config.ValidationType = ValidationType.Schema;
config.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
config.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
config.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
config.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Get the XmlReader object with the configured settings.
XmlReader reader = XmlReader.Create(path, config);
// Parsing the file will cause the validation to occur.
while (reader.Read()) ;
}
private void ValidationCallBack(object sender, ValidationEventArgs vea)
{
if (vea.Severity == XmlSeverityType.Warning)
Console.WriteLine(
"\tWarning: Matching schema not found. No validation occurred. {0}",
vea.Message);
else
Console.WriteLine("\tValidation error: {0}", vea.Message);
}
The code above assumes the following using statements.
using System.Xml;
using System.Xml.Schema;
Just to keep this simple I did not return a boolean or a collection of validation errors, you could easily modify this to do so.
Note: I modified your config.xml and config.xsd to get them to validate. These are the changes I made.
config.xsd:
<xs:element maxOccurs="unbounded" name="levelVariant">
config.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">
Following is out of a working sample:
Usage:
XMLValidator val = new XMLValidator();
if (!val.IsValidXml(File.ReadAllText(#"d:\Test2.xml"), #"D:\Test2.xsd"))
MessageBox.Show(val.Errors);
Class:
public class CXmlValidator
{
private int nErrors = 0;
private string strErrorMsg = string.Empty;
public string Errors { get { return strErrorMsg; } }
public void ValidationHandler(object sender, ValidationEventArgs args)
{
nErrors++;
strErrorMsg = strErrorMsg + args.Message + "\r\n";
}
public bool IsValidXml(string strXml/*xml in text*/, string strXsdLocation /*Xsd location*/)
{
bool bStatus = false;
try
{
// Declare local objects
XmlTextReader xtrReader = new XmlTextReader(strXsdLocation);
XmlSchemaCollection xcSchemaCollection = new XmlSchemaCollection();
xcSchemaCollection.Add(null/*add your namespace string*/, xtrReader);//Add multiple schemas if you want.
XmlValidatingReader vrValidator = new XmlValidatingReader(strXml, XmlNodeType.Document, null);
vrValidator.Schemas.Add(xcSchemaCollection);
// Add validation event handler
vrValidator.ValidationType = ValidationType.Schema;
vrValidator.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
//Actual validation, read conforming the schema.
while (vrValidator.Read()) ;
vrValidator.Close();//Cleanup
//Exception if error.
if (nErrors > 0) { throw new Exception(strErrorMsg); }
else { bStatus = true; }//Success
}
catch (Exception error) { bStatus = false; }
return bStatus;
}
}
The above code validates following xml(code3) against xsd(code4).
<!--CODE 3 - TEST1.XML-->
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Test1.xsd">
<name>My Name</name>
<street>1, My Street Address</street>
<city>Far</city>
<country>Mali</country>
</address>
<!--CODE 4 - TEST1.XSD-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
In validating against your xml/xsd I get of errors different than yours; I think this can help you continue(add/remove xml elements) from here:
You may also try the reverse process; try generating the schema from your xml and compare with your actual xsd - see the difference; and the easiest way to do that is to use generate schema using VS IDE. Following is how you'd do that:
Hope this helps.
--EDIT--
This is upon John's request, please see updated code using non deprecated methods:
public bool IsValidXmlEx(string strXmlLocation, string strXsdLocation)
{
bool bStatus = false;
try
{
// Declare local objects
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler);
rs.Schemas.Add(null, XmlReader.Create(strXsdLocation));
using (XmlReader xmlValidatingReader = XmlReader.Create(strXmlLocation, rs))
{ while (xmlValidatingReader.Read()) { } }
////Exception if error.
if (nErrors > 0) { throw new Exception(strErrorMsg); }
else { bStatus = true; }//Success
}
catch (Exception error) { bStatus = false; }
return bStatus;
}
void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: " + Environment.NewLine;
else strErrorMsg += "ERROR: " + Environment.NewLine;
nErrors++;
strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
}
Usage:
if (!val.IsValidXmlEx(#"d:\Test2.xml", #"D:\Test2.xsd"))
MessageBox.Show(val.Errors);
else
MessageBox.Show("Success");
Test2.XML
<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Test2.xsd">
<levelVariant>
<filePath>SampleVariant</filePath>
</levelVariant>
<levelVariant>
<filePath>LegendaryMode</filePath>
</levelVariant>
<levelVariant>
<filePath>AmazingMode</filePath>
</levelVariant>
</config>
Test2.XSD (Generated from VS IDE)
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="config">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="levelVariant">
<xs:complexType>
<xs:sequence>
<xs:element name="filePath" type="xs:anyURI">
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
This is guaranteed to work!
Your code to extract the schema location looks weird. Why do you get the value of the xmlns attribute and concatenate it with the value of the xsi:noNamespaceSchemaLocation attribute? The exception is caused by the fact that you cannot specify a prefix in a call to Attributes; you need to specify the desired XNamespace.
Try this (untested):
// Load document
XDocument doc = XDocument.Load("file.xml");
// Extract value of xsi:noNamespaceSchemaLocation
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
string schemaURI = (string)doc.Root.Attribute(xsi + "noNamespaceSchemaLocation");
// Create schema set
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("Schemas", schemaURI);
// Validate
doc.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
});