开发者

Why XmlDocument Validate doesn't throw any exception on xml with different namespace?

开发者 https://www.devze.com 2023-02-14 16:29 出处:网络
I validate some external XML documents against my XSD schema: <?xml version=\"1.0\" encoding=\"utf-8\" ?>

I validate some external XML documents against my XSD schema:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"       
           version="2011-03-01">
    <xs:element name="Document" type="DocumentType" />
    <xs:complexType name="DocumentType">
        <xs:sequence>
            <xs:element name="Author" type="string" minOccurs="0" />
            <xs:element maxOccurs="unbounded" name="Receiver" type="string" />
        </xs:sequence>
    </xs:complexType>

My schema doesn't use namespaces. It works well but I have problem with certain XML. It is excel file saved as XLM. It is completely invalid but my validator does not complain. It is not valid according to my schema but my method does not throw any exception! It looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<office:document-content
    xmlns:office="foo">
    <office:bar></office:bar>
</office:document-content>

here's my code:

public void Validate(Stream streamWithXML)
{
XmlReaderSettings settings = new XmlReaderSettings();

settings.Schemas.Add(settings.Schemas.Add("", xsdPath));
settings.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create(streamWithXML, settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHa开发者_开发知识库ndler eventHandler = new ValidationEventHandler(ValidationEventHandler);
document.Validate(eventHandler);
reader.Close();
}

static void ValidationEventHandler(object sender, ValidationEventArgs e)
{}

Do you have any clue? I suppose it's because that specific document has some inline namespaces declarations. However online validator at http://tools.decisionsoft.com/schemaValidate/ throws exception:

Cannot find the declaration of element 'office:document-content'.

which is correct. Is there any way to make .NET validator to throw exception in that case?


It does not throw an exception because it's not designed to.

The documentation shows that the intended usage is to create validation eventhandler and pass that into the Validate method.

http://msdn.microsoft.com/en-us/library/ms162371.aspx

This event handler contains warnings and errors if the document fails to validate, and you are expected to check this and handle validation error accordingly in the event handler you defined.

The ValidationEventArgs in your event handler contains the exception, severity, and messages:

http://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs.aspx

The code example in the first link shows the poper usage.


You need to set the ValidationFlags in the settings object to include ReportValidationWarnings.

0

精彩评论

暂无评论...
验证码 换一张
取 消