我尝试使用IXmlSerializable
和XmlSchemaProviderAttribute
序列化对象。
架构如下所示:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="BuildingsSchema" targetNamespace="BuildingModelSchema"
elementFormDefault="qualified"
xmlns="BuildingModelSchema"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="buildings">
<xs:complexType>
<xs:sequence>
<xs:element name="building" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
...
获取架构的代码如下所示(找到here):
[<Literal>]
let XML_NAMESPACE = "BuildingModelSchema"
[<Literal>]
let XSD_SCHEMA_PATH = @"BuildingsSchema.xsd"
[<XmlSchemaProvider(BuildingsSchema)>]
type BuildingsStatistics() =
interface IXmlSerializable with
...
static member BuildingsSchema(xs: XmlSchemaSet) =
let serializer = new XmlSerializer(typeof<XmlSchema>)
let schema = (serializer.Deserialize(new XmlTextReader(XSD_SCHEMA_PATH), null)) :?> XmlSchema
xs.XmlResolver <- new XmlUrlResolver()
xs.Add(schema) |> ignore
new XmlQualifiedName("buildings", XML_NAMESPACE)
...
现在,当我尝试使用XmlSerializer
序列化对象时,我得到一个异常:
{&#34; PlanerModel.BuildingsStatistics.BuildingsSchema()必须返回有效的类型名称。类型&#39;建筑物&#39;无法在targetNamespace =&#39; BuildingModelSchema&#39;中找到。&#34;}
修改
尝试反序列化有效的测试文档后,我得到相同的错误消息。我希望xml架构有问题,但由于这是我第一次使用xml架构,我似乎没有发现错误。
进一步测试显示在XmlSerializer
:
XmlSerializer ser = new XmlSerializer(typeof(BuildingsStatistics)); // Exception is thrown here
ser.Deserialize(...) // Will not be executed
此外,XmlSchema
方法中添加的BuildingsSchema
不包含任何元素(在我的情况下为0个元素和14个全部为&#39;空的&#39;(无行号) ,位置等))。