XML validation with XSD file - c#

I try to validate my xml structure, using an xml schema.
This code sample is given here : https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.validate?view=net-5.0
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
// the following call to Validate succeeds.
document.Validate(eventHandler);
// add a node so that the document is no longer valid
XPathNavigator navigator = document.CreateNavigator();
navigator.MoveToFollowing("price", "http://www.contoso.com/books");
XmlWriter writer = navigator.InsertAfter();
writer.WriteStartElement("anotherNode", "http://www.contoso.com/books");
writer.WriteEndElement();
writer.Close();
// the document will now fail to successfully validate
document.Validate(eventHandler);
Problem is that when I'm using a non valide xml document, I already have an exception of type System.Xml.Schema.XmlSchemaValidationException on line :
XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
Does this mean you dont need to use this Validate(eventHandler) method with C# 6 anymore ? Or will it take care of few specific validation problems ?

Related

Review that the XML parsed here is from a trusted source, otherwise set settings.DtdProcessing to System.Xml.DtdProcessing.Prohibit or .Ignore

Rule:
Do not allow Dtd on XmlTextReader
Category:
Microsoft.Security.Xml
Check Id:
CA3054
Rule Description:
Prohibit DTD processing when using XmlTextReader on untrusted sources. Enabling DTD processing on the XML reader and using UrlResolver for resolving external XML entities may lead to information disclosure. Content from file system or network shares for
the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector.
Rule File:
securityxmlrules.dll [14.0.0.0]
Help:
http://go.microsoft.com/fwlink/?LinkId=282614&clcid=0x409
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
StringReader stringReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(stringReader);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlAttributeCollection attrs = doc.DocumentElement.Attributes;
if (!string.IsNullOrWhiteSpace(cookie))
{
string pagingcookie = GetPagingCookie(cookie);
if (!string.IsNullOrWhiteSpace(pagingcookie))
{
XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
pagingAttr.Value = pagingcookie;
attrs.Append(pagingAttr);
}
}
How to resolve this FxCop for SDL
You created a settings object but your XmlReader doesn't actually use it. You need to create an XmlReader with the settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
StringReader stringReader = new StringReader(xml);
XmlReader reader = XmlReader.Create(stringReader, settings);

How to check if XMLReader has valid XML without reading so as to write complete using XMLWriter?

I'm trying to write a string(which is nothing but XMLNodes) into a new XML File using XMLWriter. Few of the strings are valid XML content while few of the string aren't.
String Input:
1.
<Test>
<A a="Hello"></A>
<B b="Hello"></B>
</Test>
Hello
This is Sample String but not XML
Code :
using (XmlWriter writer = XmlWriter.Create(#"C:\\Test.XML"))
{
writer.WriteStartDocument();
string scontent2 = "Hello This is Sample String but not XML";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
try{
using (StringReader stringReader = new StringReader(scontent))
using (XmlReader xmlReader = XmlReader.Create(stringReader, settings))
{
writer.WriteStartElement("Test");
writer.WriteNode(xmlReader, true);
writer.WriteEndElement();
}catch(XMLException exception){}
}
Expected Output:
The Test element must also not be created if the Exception occurs. If I use, scontent.Read() or any such, the problem is since the pointer moves to a node, the writer.WriteNode(scontent,true) wont write entire nodes(if there are more than two nodes) For ex. <A a="Hello"></A><B b="Hello"></B>. In this case, I've write all nodes using WriteNode for which XMLReader must be in Initial State(XmlReader.State).

Validate Xml with Xsd and update Xml

i am validating a Xml file with an existing Xsd schema. Is it possible to update the Xml with the xsd file if the validation fails?
After Error you can execute this code
var schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema1.xsd");
// add further schemas as needed
schemaSet.Compile();
var xmlSampleGenerator= new XmlSampleGenerator(schemaSet, new XmlQualifiedName("Test"));
var doc = new XmlDocument();
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
xmlSampleGenerator.WriteXml(writer);
}
Link : http://msdn.microsoft.com/en-us/library/aa302296.aspx

Generated CS class from xml schema

I did generate C# class form scham using xsd.exe (VS 2010 command prompt),
but when I serialize class to xml file, in the out file I don't have entry for schema.
Serialized xml:
<?xml version="1.0" encoding="utf-16"?>
<Dokumenty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" idSystemuLokalnego="ASD" dataUtworzenia="0001-01-01T00:00:00">
<Wniosek>
<Beneficjent />
</Wniosek>
When I try to validate with schema using code:
//Serilalize xml to string
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
x.Serialize(xw, doc);
String xml = sw.ToString();
StringReader sr = new StringReader(xml);
XmlTextReader xtr = new XmlTextReader(sr);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", "schemas\\SimWniosekApl_v2.0.xsd");
settings.ValidationType = ValidationType.Schema;
//XmlReader reader = XmlReader.Create(xtr);
XmlDocument document = new XmlDocument();
document.Load(xtr);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler);
// the following call to Validate succeeds.
document.Validate(eventHandler);
It fails with exception:
Additional information: The XmlSchemaSet on the document is either null or has no schemas in it. Provide schema information before calling Validate.
What do I do wrong?
you need to apply the XmlReaderSettings when you create the reader.
That code does nothing with the settings. The reader has been created already, before the settings are created. The code simply creates settings and then forgets them.
StringReader sr = new StringReader(xml);
//XmlTextReader xtr = new XmlTextReader(sr);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", "schemas\\SimWniosekApl_v2.0.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xtr,settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler);
document.Validate(eventHandler);
There is a full example here:
http://msdn.microsoft.com/en-us/library/ms162371.aspx

Deprecated XML validation code problem C#

I'm trying to figure out how to correct his deprecated xml schema validation code.
public static bool ValidateXml(string xmlFilename, string schemaFilename)
{
⁞
//Forward stream reading access to data
XmlTextReader forwardStream = new XmlTextReader(xmlFilename);
//deprecated way of checking agaisnt a schema -- update.
//xmlreader class.
XmlValidatingReader validation = new XmlValidatingReader(forwardStream);
validation.ValidationType = ValidationType.Schema;
//XmlReader validator = new XmlReader.Create(
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add(null, schemaFilename);
validation.Schemas.Add(schemas);
⁞
you need to use XmlReader and XmlReaderSettings instead of deprecated classes. Below is an example:
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add("urn:bookstore-schema", "books.xsd");
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);
// Parse the file.
while (reader.Read());
more details here: Validating XML Data with XmlReader

Categories

Resources