I am having trouble validating serialized data.
Ok, so I started with an XSD file which I got from some third party. Generated C# classes using xsd tool. Then I added
[XmlAttribute("noNamespaceSchemaLocation", Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
public string SchemaLocation = "http://localhost/schemas/AP_Transactions_10052011.xsd";
to the top level object. The URL in question is obviously accessible from my machine where I am running the code. Then I am serializing it using XmlSerializer, which correctly produces
<?xml version="1.0" encoding="utf-8"?>
<BU_AP_Vendor_Invoices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="http://local.com/schemas/AP_Transactions_10052011.xsd">
...
</BU_AP_Vendor_Invoices>
So far so good.
Now I am trying to validate the file like so:
public static void Validate(TextReader xmlData)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += delegate(object sender, ValidationEventArgs args)
{
Console.WriteLine(args.Message);
};
using (XmlReader xmlReader = XmlReader.Create(xmlData, settings))
while (xmlReader.Read()) ;
}
Which results Could not find schema information for the element 'element name' warnings for every element in the XML file. I assume that means the XSD is simply not being loaded.
I was looking at the XmlReaderSettings.Schemas, but how would the reader know what to add there? I assumed that if I don't add schemas explicitly then magic will simply happen, but that doesn't seem to work.
Question is how to do this properly?
Please take a look at this post; the gist is to use XmlSchemaValidationFlags.ProcessSchemaLocation.
Related
I am trying to validate a xml file againg a xsd, but for some reason the following Errorr occures.
Strange is that different programms, which do the same does not show an error.
How can i change the settings for the xsd to not check for missing attributes and just ignore them?
Code:
static void ValidateXml(string xmlFile, string xsdFile)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, xsdFile);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += ValidationEventHandler;
using (XmlReader reader = XmlReader.Create(xmlFile, settings)) // failing here
{
while(reader.Read())
{
// Reading and doing nothing with the xml file.
}
}
}
Error Message:
System.Xml.Schema.XmlSchemaValidationException: "The 'http://www.w3.org/XML/1998/namespace:lang' attribute is not declared."
I tried it using XMlDocument, but that doesnt work for me, cause i am reading of xml files up to 2 gb.
I am using XmlSerializer in C# to generate an XML document based on a model. I need to generate the following XML root that contains a duplicate namespace using separate prefixes. Below is what the output should look likeā¦
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:hl7-org:v3 CDA_SDTC.xsd"
xmlns="urn:hl7-org:v3"
xmlns:cda="urn:hl7-org:v3"
xmlns:sdtc="urn:hl7-org:sdtc">
However, when I Serialize this, the default entry is removed (which contains the duplicate namespace) and the root is prefixed.
<cda:ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance" xmlns:cda="urn:hl7-org:v3">
Here is my XmlSerializer code...
var writer = new XmlSerializer(clinicalDocument.GetType(),"urn:hl7-org:v3");
var myNamespace = new XmlSerializerNamespaces();
myNamespace.Add("sdtc", "urn:hl7-org:sdtc");
myNamespace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
myNamespace.Add("cda", "urn:hl7-org:v3");
using (var file = new System.IO.StreamWriter(CCDUncOutputPath))
{
writer.Serialize(file, clinicalDocument, myNamespace);
file.Close();
};
writer = null;
GC.Collect();
Does anyone have a fix for this?
I am working with Mismo 2.3.1, dtd based schema. I converted the dtd to xsd and then generated c# code to serialize/deserialze object representations of the xml doc.
Given a valid mismo 2.3.1 xml doc, I can deserialize into my generated C# class.
I have code working to use XmlSerializer along with XmlReaderSettings and XmlSchmeas collection, reading in my converted xsd.
If I put xmlns="http://mySchema..." in the root element, and try to validate intentionally invalid xml, works as expected, my validation event gets pinged with accurate description.
If I take out the xmlns attribute, then i get "could not find schema information for element [my root element]"
Any idea on how to validate xml that comes in without the xmlns spec? Any settings to say to the serializer "use this schema when you come across this element"?
Thanks in advance!
static void Main() {
var settings = new XmlReaderSettings();
settings.NameTable = new NameTable();
var nsMgr = new XmlNamespaceManager(settings.NameTable);
nsMgr.AddNamespace("", "http://example.com/2013/ns"); // <-- set default namespace
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, #"C:\XSDSchema.xsd"); // <-- set schema location for the default namespace
var parserCtx = new XmlParserContext(settings.NameTable, nsMgr, XmlSpace.Default);
using (var reader = XmlReader.Create(#"C:\file.xml", settings, parserCtx)) {
var serializer = new XmlSerializer(typeof(Foo));
Foo f = (Foo)serializer.Deserialize(reader);
}
}
I'm trying to read a xml-file with it's schema.
My xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PersonList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="D:\MySchema.xsd">
Now I'm reading the xml file like this:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
using (XmlReader reader = XmlReader.Create("MyXmlFile.xml", settings))
{
while(reader.Read())
//.....
}
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);
}
The problem is that when the schema 'D:\MySchema.xsd' is not found, it's still reading the xml so noNamespaceSchemaLocation is useless...
So I've set the Schema path in my code like this:
settings.Schemas.Add(null, "D:\\MySchema.xsd");
And now it's reading the xml file by using the schema, but I'm setting here the schema path hardcoded...
I want to get the schema path (noNamespaceSchemaLocation) from the xml file and add the schema to the settings depending on the schema from the xml file. By doing it like this, I can also check if the Schema exists or not.
To make it clear: How can I get the noNamespaceSchemaLocation from a xml file?
xsi:noNamespaceSchemaLocation="anyURI"
You probably need to specify the location as a uri, so something like file://d:/myschema.xsd
Why can't the framework load the value of noNamespaceSchemaLocation attribute as it is the standard attribute defined for the class? Could be an enhancement to XML library to load the noNamespaceSchemaLocation attribute value to some property under Schemas so that it will be easier for developer to extract the value and check if the file exists or not and proceed to validate the Xml.
Have have been trying to make a validator for my xml files. I have used some of the other examples that can be found on this site (like How to validate an XML document?).
I just don't see it working the way I expect. What does actually get validated?
Almost no matter what I change in the xml file, the validator dosent sees it as an error. I thought the validator would see if the xml file contains an element not defined in the xsd. The validator only catches normal xml syntax errors.
So whats the point of using the xsd if it doesn't have an influence?
My validator
string xsd_file = "Message.xsd";
XmlSchema xsd = new XmlSchema();
xsd.SourceUri = xsd_file;
XmlSchemaSet ss = new XmlSchemaSet();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
ss.Add(null, xsd_file);
if (ss.Count > 0)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(ss);
settings.Schemas.Compile();
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
XmlTextReader r = new XmlTextReader(filepath);
using (XmlReader reader = XmlReader.Create(r, settings))
{
try
{
while (reader.Read())
{
}
}
catch (XmlException ex)
{
throw;
}
}
}
The code for the validation eventhandler is missing.
Looking at my working code which is slightly different I have this
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationFlags;
Can't remember why I had to add it though.
First thing to do is make sure the eventhandler is getting triggered, after that it may be a problem with your xsd.