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
Related
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 ?
Using C#, I can easily serialize a class instance to an XML:
XmlSerializer xsSubmit = new XmlSerializer(typeof(Parking));
using (StringWriter sww = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings { Indent = true }))
{
xsSubmit.Serialize(writer, myParking);
var xml = sww.ToString();
File.WriteAllText("myParking.xml", xml);
}
I can also create an XSD file for this class, using XSD.exe.
It is indeed possible to inline an XSD in an XML file (ref. https://msdn.microsoft.com/en-us/library/ms759142(v=vs.85).aspx)
How can I get, in C#, my instance as an XML having its XSD definition inlined in it?
Using the following MSDN documentation I validate an XML file against a schema: http://msdn.microsoft.com/en-us/library/8f0h7att%28v=vs.100%29.aspx
This works fine as long as the XML contains a reference to the schema location or the inline schema. Is it possible to embed the schema "hard-coded" into the application, i.e. the XSD won't reside as a file and thus the XML does not need to reference it?
I'm talking about something like:
Load XML to be validated (without schema location).
Load XSD as a resource or whatever.
Do the validation.
Try this:
Stream objStream = objFile.PostedFile.InputStream;
// Open XML file
XmlTextReader xtrFile = new XmlTextReader(objStream);
// Create validator
XmlValidatingReader xvrValidator = new XmlValidatingReader(xtrFile);
xvrValidator.ValidationType = ValidationType.Schema;
// Add XSD to validator
XmlSchemaCollection xscSchema = new XmlSchemaCollection();
xscSchema.Add("xxxxx", Server.MapPath(#"/zzz/XSD/yyyyy.xsd"));
xvrValidator.Schemas.Add(xscSchema);
try
{
while (xvrValidator.Read())
{
}
}
catch (Exception ex)
{
// Error on validation
}
You can use the XmlReaderSettings.Schemas property to specify which schema to use. The schema can be loaded from a Stream.
var schemaSet = new XmlSchemaSet();
schemaSet.Add("http://www.contoso.com/books", new XmlTextReader(xsdStream));
var settings = new XmlReaderSettings();
settings.Schemas = schemaSet;
using (var reader = XmlReader.Create(xmlStream, settings))
{
while (reader.Read());
}
You could declare the XSD as an embedded resource and load it via GetManifestResourceStream as described in this article: How to read embedded resource text file
Yes, this is possible. Read the embedded resource file to string and then create your XmlSchemaSet object adding the schema to it. Use it in your XmlReaderSettings when validating.
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
I am editing csproj files with Linq-to-XML and need to save the XML without the <?XML?> header.
As XDocument.Save() is missing the necessary option, what's the best way to do this?
You can do this with XmlWriterSettings, and saving the document to an XmlWriter:
XDocument doc = new XDocument(new XElement("foo",
new XAttribute("hello","world")));
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, settings))
// or to write to a file...
//using (XmlWriter xw = XmlWriter.Create(filePath, settings))
{
doc.Save(xw);
}
string s = sw.ToString();
A simpler solution than the accepted answer is to use XDocument.ToString() to get the XML text without the header.
Example:
// Load the file
XDocument xDocument = XDocument.Load(fileName);
// Edit the XML...
// Save the edited XML text to file
File.WriteAllText(fileName, xDocument.ToString());