How to validate xml code file though .NET? + How would I do it if I use XML serialization?

I want users to be able to export data as an XML file. Of course I want them to be able to later on import that same XML file however they always could change it or it could be a different XML file.

So I want to validate the XML file to check if it is in the format that I expect. So I guess I would need something like a schema to check just that it has to be through code.

So if I expect

<Root>
 <Something>
    <SomethingElse> </SomethingElse>
 </Something>
</Root>

I don’t want some other format to be in the file other then the one I expect.

Also how would I validate fields? Like say I require that there must be some text in between tags. If it is blank the file is not valid.

So how could I do this?

Edit

I decided to use XML serialization so I know it will through an exception if it is the wrong format and ignore stuff that does not work. However I am not sure should I just go through it and C# to validate each of the records or should I try to make an xml schema to do it.

If I would want to do it through an xml schema with xml serialization how would that work? Like Do I first do something like I seen in the responses then de serialize it? Or how would I do it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here’s a code snippet that you can use to do so:

using (FileStream stream = File.OpenRead(xsdFilepath))
{
    XmlReaderSettings settings = new XmlReaderSettings();

    XmlSchema schema = XmlSchema.Read(stream, OnXsdSyntaxError);
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(schema);
    settings.ValidationEventHandler += OnXmlSyntaxError;

    using (XmlReader validator = XmlReader.Create(xmlPath, settings))
    {
        // Validate the entire xml file
        while (validator.Read()) ;
    }
}

The OnXmlSyntaxError function will be called when a syntax error occur.

Method 2

There are a few ways to validate XML files. Check out How To Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET

Also see Validating an XML against Referenced XSD in C# example

Another good example is Validate XML against XSD using code at runtime in C#

Here is the code from the last post:

public void ValidateXmlDocument(
    XmlReader documentToValidate, string schemaPath)
{
    XmlSchema schema;
    using (var schemaReader = XmlReader.Create(schemaPath))
    {
        schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
    }

    var schemas = new XmlSchemaSet();
    schemas.Add(schema);

    var settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = schemas;
    settings.ValidationFlags =
        XmlSchemaValidationFlags.ProcessIdentityConstraints |
        XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationEventHandler += ValidationEventHandler;

    using (var validationReader = XmlReader.Create(documentToValidate, 
           settings))
    {
        while (validationReader.Read()) { }
    }
}

private static void ValidationEventHandler(
    object sender, ValidationEventArgs args)
{
    if (args.Severity == XmlSeverityType.Error)
    {
        throw args.Exception;
    }
    Debug.WriteLine(args.Message);
}

Method 3

You can use LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387037.aspx. This page also shows how to do that along with source to dump any invalid nodes: http://blogs.msdn.com/xmlteam/archive/2007/03/03/the-new-linq-to-xml-bridge-classes-to-system-xml.aspx

Method 4

Validate XML file with Schema in .NET

Method 5

You can use xml serialization in your classes:

[XmlType("Root", Namespace = "http://example.com/Root")]
[XmlRoot(Namespace = "http://example.com/Root.xsd", ElementName = "Root", IsNullable = false)]
public class Root {
  [XmlElement("Something")] 
  public Something Something { get; set; }
}

public class Something {
  [XmlElement("SomethingElse")]
  public SomethingElse SomethingElse { get; set; }
}

public class SomethingElse {
  [XmlText]
  public string Text { get; set; }
}

Serialize it like this:

var serializer = new XmlSerializer(typeof(Root));
serializer.Serialize(outputStrem, myRoot);

You can then test before deserializing, e.g.:

var serializer = new XmlSerializer(typeof(Root));
string xml = @"
  <Root xmlns='http://example.com/Root'>
    <Something>
      <SomethingElse>Yep!</SomethingElse>
    </Something>
  </Root>"; // remember to use the XML namespace!
Debug.Assert(serializer.CanDeserialize(new XmlTextReader(new StringReader(xml))));

And then to deserialize simply:

Root newRoot = (Root)serializer.Deserialize(inputStream);

Your XSD is implicit. It matches your classes. To use richer XSDs, you can venture into Schema Providers.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x