Invalid XDocument is getting validated

情到浓时终转凉″ 提交于 2021-02-05 09:31:13

问题


I have following xml schema

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attributeFormDefault="unqualified" elementFormDefault="qualified" 
           targetNamespace="http://www.MySchema.net" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="RootElement">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="name" type="xs:string" />
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

and following xml's are validated against above schema:

Case 1: (Schema exception)

<?xml version="1.0" encoding="utf-8" ?> <RootElement11 name="Configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.MySchema.net Root" xmlns="http://www.MySchema.net">
    </RootElement11>

Case 2: (No exception)

<?xml version="1.0" encoding="utf-8" ?>
<RootElement11 name="Configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.YourSchema.net Root" xmlns="http://www.YourSchema.net">
</RootElement11>

Case 3: (No exception)

<RootElement11 name="Configuration">
</RootElement11>

For Case 1, I get an expected exception that "The 'http://www.MySchema.net:RootElement1' element is not declared.", but Case 2 and Case 3 are validated without exception.

I wanted to know if there is a possibility to throw an exception when xml files with false namespaces or without namespaces are validated using XDocument.Validate method.

I found some info which use XmlReader with settings to throw these type of exception. I see two possibilites 1) Get back to XmlReader from XDocument, 2) Validate using XmlReader and use XDocument to do LINQ queries. But is it possible to accomplish this without XmlReader.


回答1:


The issue is that both cases 2 and 3 are valid per the schema - your schema doesn't have any opinion on elements in namespaces other than its targetNamespace.

XmlReader can return a warning for this, but there's no overload for XDocument that will do it. The snippet in your linked question uses an XmlReader wrapper around XDocument, I can't see why you'd have any issue with doing it this way.



来源:https://stackoverflow.com/questions/37304659/invalid-xdocument-is-getting-validated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!