【发布时间】:2017-12-11 08:28:20
【问题描述】:
我不明白为什么 C# 代码生成器(xsd、xsd2code)会生成输出类 Profile,其中两个相同类型的属性标有不同的属性。其中一个被标记为不合格,一个则不是。
我的 XSD 如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.acme.com" xmlns="http://www.acme.com" elementFormDefault="unqualified">
<xsd:complexType name="ParameterList">
<xsd:sequence>
<xsd:element ref="Parameter" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ParameterItem">
<xsd:sequence>
<xsd:element name="Name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="Value" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="Parameters" type="ParameterList" />
<xsd:element name="Parameter" type="ParameterItem" />
<xsd:element name="Profile">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Parameters" minOccurs="1" maxOccurs="1"/>
<xsd:element name="Parameters" type="ParameterList" minOccurs="1" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
以及xsd2code生成的输出代码:
using System.Collections.Generic;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace SO2_installation
{
public class ParameterList
{
public ParameterList()
{
Parameter = new List<ParameterItem>();
}
public List<ParameterItem> Parameter { get; set; }
}
public class ParameterItem
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Profile
{
public Profile()
{
Parameters1 = new List<ParameterItem>();
Parameters = new List<ParameterItem>();
}
[XmlArray(Order = 0)]
[XmlArrayItem("Parameter", IsNullable = false)]
public List<ParameterItem> Parameters { get; set; }
[XmlArray("Parameters", Form = XmlSchemaForm.Unqualified, Order = 1)]
[XmlArrayItem("Parameter", IsNullable = false)]
public List<ParameterItem> Parameters1 { get; set; }
}
}
代码已被 R# 简化,因此它不是 xsd2code 的确切输出,但它显示了困扰我的问题 - 为什么两个属性没有标记相同的属性?
这是在准备与 XSD 对应的 XML 文件时出现的问题。它应该如下所示,这使得准备工作很容易出错。
<?xml version="1.0" encoding="utf-8"?>
<Profile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Parameters xmlns="http://www.acme.com">
<Parameter xmlns="http://www.acme.com">
<Name xmlns="">SERIALNUMBER</Name>
<Value xmlns="">600001</Value>
</Parameter>
</Parameters>
<Parameters1 xmlns="">
<Parameter xmlns="http://www.acme.com">
<Name xmlns="">SERIALNUMBER</Name>
<Value xmlns="">600002</Value>
</Parameter>
</Parameters1>
</Profile>
问题的答案:“为什么相同类型的两个属性,基于相同的 xsd 标记有不同的属性”不是我主要关心的问题。由于我无法更改 XSD 文件(它们是很久以前发送给客户端的),我需要找到一种方法来使用 XML 文件,无论它们的元素是否标有名称空间。目前,当我传递 XML 时,例如:
<Parameters1 xmlns="http://www.acme.com">
XmlSerializer 将返回解析错误。发送带有命名空间或不带命名空间的所有参数的 XML 会很好 - 只要它们被一致地标记就没有关系。
提前感谢您帮助我解决这个问题。
附加说明:该示例是为了简化附加代码而准备的,因此请不要关心 Profile 包含两个相同类型的属性。
【问题讨论】: