【问题标题】:Why does xsd.exe generate a schema that makes all attributes required?为什么 xsd.exe 会生成一个架构,使得所有属性都是必需的?
【发布时间】:2013-09-08 16:54:37
【问题描述】:

在我的代码中,我有以下类来反序列化 XML:

public abstract class AssetBase
{
    [XmlAttribute] public string Name { get; set; }
    [XmlAttribute] public float RelativeX { get; set; }
    [XmlAttribute] public float RelativeY { get; set; }
    [XmlAttribute] public float RelativeZ { get; set; }
    [XmlAttribute] public float ScaleX { get; set; }
    [XmlAttribute] public float ScaleY { get; set; }
    [XmlAttribute] public bool Visible { get; set; }
}

当我使用xsd.exe 为此定义架构时,架构会对其进行设置,因此需要这些属性进行验证。

如何设置此类,以便用户可以将其留空,因为并非所有这些都是强制性的?


编辑: 我只是查看了它生成的 xsd 并看到:
  <xs:complexType name="AssetBase" abstract="true">
    <xs:attribute name="Name" type="xs:string" />
    <xs:attribute name="RelativeX" type="xs:float" use="required" />
    <xs:attribute name="RelativeY" type="xs:float" use="required" />
    <xs:attribute name="RelativeZ" type="xs:float" use="required" />
    <xs:attribute name="ScaleX" type="xs:float" use="required" />
    <xs:attribute name="ScaleY" type="xs:float" use="required" />
    <xs:attribute name="Visible" type="xs:boolean" use="required" />
  </xs:complexType>

我很困惑为什么没有将 Name 设置为必需,但其余的都是...

【问题讨论】:

  • 是不是因为string 可以为空而其他类型(floatbool)不是?只是猜测。
  • 这是个好主意。不幸的是,xsd.exe 似乎无法处理 float?bool? 属性,因为它在它们上失败了。使用[XmlElement] 会生成一个 xsd,但它需要一个列为 nil 的完整元素节点,并且不允许您不指定它:-/
  • 您是否尝试过将[XmlRoot(IsNullable=true)] 添加到AssetBase 以允许可空类型使用属性正确序列化

标签: c# xml xsd-validation


【解决方案1】:

正如您所发现的那样,Nullable&lt;T&gt; 不仅仅适用于 [XmlAttribute],因为它是一种复杂类型。您必须使用 *Specified 的 'magic' 属性来处理这个问题。

[XmlIgnore]
public float? RelativeX
{
    get { return this.RelativeX; }
    set { this.RelativeX = value; }
}

[XmlAttribute("RelativeX")]
public float RelativeXValue
{
    get { return this.RelativeX.Value; }
    set { this.RelativeX = value; }
}

[XmlIgnore]
public bool RelativeXValueSpecified
{
    get { return this.RelativeX.HasValue; }
}

您的其他选择是:

  • 为所有属性使用字符串并具有正确类型的相应属性
  • 实施IXmlSerializable

【讨论】:

  • 这将如何帮助 XSD 生成? XMLAttribute 值仍然是不可为空的类型,这将导致 xsd.exe 使 xsd 生成为 required
  • XmlSerializer 应该看到 Specified 属性并推断它是可选的。如果 RelativeXValueSpecified 为 false,则该属性将被完全忽略。
【解决方案2】:

我找到了这个解释:

使用属性:从类生成 XML Schema 文档

以下两种情况,Xsd.exe不指定use属性,恢复为默认值可选:

• 存在遵循指定命名约定的额外公共 bool 字段。

• 通过 System.ComponentModel.DefaultValueAttribute 类型的属性为成员分配默认值。

如果这两个条件都不满足,Xsd.exe 会为 use 属性生成 required 值。

来自this article

我使用了默认值的方式,效果很好:)

享受!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2010-11-21
    • 2020-07-10
    • 2020-04-12
    • 2013-10-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多