0

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.

Community
  • 1
  • 1
lerner1225
  • 862
  • 7
  • 25
  • I would create an extension method for XDocument, and in that method use XmlReader over XDocument.CreateReader for validation. So basically 2nd method. – Evk May 18 '16 at 16:10
  • Possible duplicate of [XDocument.Validate is always successful](http://stackoverflow.com/questions/17232575/xdocument-validate-is-always-successful) – Charles Mager May 18 '16 at 16:11

1 Answers1

2

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.

Community
  • 1
  • 1
Charles Mager
  • 25,735
  • 2
  • 35
  • 45