.net XmlReader从模式中获取元素默认值
关于.net XmlReader从模式中获取元素默认值,.net,xsd,xmlreader,.net,Xsd,Xmlreader,关于XmlReader,这可能是一个幼稚的问题,但我还没有在MSDN文档中找到答案 假设我有XSDSchemaTest.XSD <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pageSettings"> <xs:complexType> <x
XmlReader
,这可能是一个幼稚的问题,但我还没有在MSDN文档中找到答案
假设我有XSDSchemaTest.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>
我尝试用XmlReader
阅读本文档,如下所示
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();
}
}
当前,我收到一个系统.FormatException
指示元素宽度
上的内容格式不正确。似乎reader
正在尝试读取元素中的内容,并且没有默认为架构中指定的默认值。正确的处理方法是什么
此外,我的理解是,对于元素,模式仅在元素显示为空内容时提供默认值,而在缺少元素时不提供默认值。这是否意味着无法为缺少的可选元素获取默认值?至于使用空元素,请设置
settings.ValidationType=ValidationType.Schema
,您应该根据需要获取默认值
关于缺少的元素,这些元素被认为是缺少的;-)因此没有默认值。理论上,您可以解析模式(例如,使用模式对象模型)以获得默认值。但这将违反规范
您是否考虑过使用属性,如
?在这种情况下,您应该为缺少的属性获取默认值。settings.ValidationType=ValidationType.Schema完成了这项任务。非常感谢。
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();
}
}