简体   繁体   中英

Get noNameSpaceSchemaLocation from xml file

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"

您可能需要将位置指定为uri,因此类似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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM