Jir
Jir

Reputation: 3145

Cannot use a referenced XML schema file (xsd) in a C# project

I defined a very simple XML schema, called MySchema, which I added to the references of my project:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="MySchema"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="UserList">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="User" type="xs:string" minOccurs="0" maxOccurs="unbounded">
        </xs:element>
      </xs:sequence>
      <xs:attribute name="id" type="xs:ID" use="required"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

On which I should be able to use XmlDocument.GetElementById.

My sample XML file is

<?xml version="1.0" encoding="UTF-8"?><UserList id="local"/>

However, when I run GetElementById("local") I still get a "NullReferenceException".

I guess I need to do something more than just adding the xsd file to the reference. Can somebody tell me where I'm going wrong please?

Upvotes: 0

Views: 399

Answers (2)

D Stanley
D Stanley

Reputation: 152566

Looks like XmlDocument.GetElementById doesn't support ID attributes defined in XSD schemas, only DTDs:

The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return null.

You can use SelectSingleNode with traditional XPath, however:

doc.DocumentElement.SelectSingleNode("//UserList[@id='local']")

Upvotes: 1

Maslow
Maslow

Reputation: 18746

If you don't define a DTD or XSD to define what id is then the GetElementById method does not work.

If you are defining an XSD or DTD in the code you don't show, then update your question.

The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return Nothing.

http://www.xtremevbtalk.com/showthread.php?t=313101

Based on the XSD at the top of the post, I'd say you aren't loading the xsd into the XmlDocument instance so that it knows which is the xs:id

Upvotes: 1

Related Questions