XmlReader gets default element from schema
This is probably a naive question about XmlReader
, but I didn't get an answer in the MSDN docs.
Suppose XSD SchemaTest.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="pageSettings">
<xs:complexType>
<xs:sequence>
<xs:element name="width" type="xs:decimal" default="8.5" minOccurs="0"/>
<xs:element name="height" type="xs:decimal" default="11" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
a well-formed XML
document SchemaTest.xml
conforming to this pattern
<?xml version="1.0" encoding="utf-8" ?>
<pageSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="SchemaTest.xsd">
<width/>
<height>11</height>
</pageSettings>
and that I am trying to read this document with the XmlReader
following.
static void Main(string[] args) {
decimal width;
decimal height;
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.Schemas.Add(null, "C:\\Projects\\SchemaTest\\SchemaTest\\SchemaTest.xsd");
using (XmlReader reader = XmlReader.Create("C:\\Projects\\SchemaTest\\SchemaTest\\SchemaTest.xml", settings)) {
reader.ReadStartElement();
if (reader.Name == "width") {
width = reader.ReadElementContentAsDecimal("width", "");
// if fail, width = default from schema
}
if (reader.Name == "height") {
height = reader.ReadElementContentAsDecimal("height", "");
// if fail, height = default from schema
}
reader.ReadEndElement();
}
}
I am currently getting System.FormatException
indicating that the content of the element width
is not in the correct format. It looks like it is reader
trying to read the content in the element and has no default value specified in the schema. What is the correct way to handle this?
Also, I understand that for elements, the schema only contains a default value if the element appears with empty content, but it does not provide a default value if the element is not present. Does this mean that there is no way to get the default value for optional elements that are missing?
source to share
As for working with empty elements, set settings.ValidationType = ValidationType.Schema
and you should get the default.
As far as missing elements are concerned, they are considered, well, missing ;-) and therefore have no default value. In theory, you can parse the schema (for example, using the schema object model) to get the default. But that would be against the specification.
Have you considered using attributes, for example <pageSettings height="55"/>
? In this case, you should get the default values for the missing attributes.
source to share