XSD:如何在子元素类型中设置属性值?

时间:2010-11-16 21:29:53

标签: c++ xsd xsd.exe codesynthesis

在xsd文件中,我有这个元素基类型:

<xs:complexType name="event" abstract="true" >
    <xs:attribute name="move" type="aos:move_ref" use="required" />
    <xs:attribute name="type" type="aos:event_type" use="required" />
</xs:complexType>

我想在子类型中定义type属性的值,所以我尝试了这个:

<xs:complexType name="signal" >
    <xs:complexContent>
      <xs:extension base="aos:event">
        <xs:attribute name="type" type="aos:event_type" fixed="signal" />
        <xs:attribute name="source" type="aos:signal_source" use="required" />
      </xs:extension>
    </xs:complexContent>
 </xs:complexType>

Visual Studio似乎并不打扰,但CodeSynthesis C++ code generator似乎不同意:

  

错误:属性'type'已经存在   在基础

中定义

我该怎么写?我只希望type属性的值特定于每个不同的子类型。

编辑----

为了使问题更清楚,我会写一些我想要做的事情但是在C ++中。

这是基类:

class Event
{
public:

   std::string name() const { return m_name; }

protected:

   // we need the child class to set the name
   Event( const std::string& name ) : m_name( name ) {} 

   // it's a base class
   virtual ~Event(){}

private:

   std::string m_name;

};

现在,其中一个孩子可以像这样实施:

class Signal : public Event
{
public:

   Signal() : Event( "signal" ){}

};

如您所见,子类定义由基类定义的属性的值。甚至可以在xsd中表达吗?

1 个答案:

答案 0 :(得分:2)

要派生类型并修复值,请使用restriction

<xs:complexType name="signal" >
    <xs:complexContent>
      <xs:restriction base="aos:event">
        <xs:attribute name="type" type="aos:event_type" fixed="signal" use="required" />
        <xs:attribute name="source" type="aos:signal_source" use="required" />
      </xs:restriction>
    </xs:complexContent>
 </xs:complexType>

通过阅读规范,我希望你couldn't add attributes in a restriction,除非基类型有attribute wildcard,但W3C XSD验证器接受上述内容。如果遇到问题,可以将定义分解为限制和扩展名:

<xs:complexType name="fixedSignalEvent">
  <xs:complexContent>
    <xs:restriction base="aos:event">
      <xs:attribute name="type" type="aos:event_type" fixed="signal" use="required" />
    </xs:restriction>
  </xs:complexContent>
</xs:complexType>

<xs:complexType name="signal" >
  <xs:complexContent>
    <xs:extension base="aos:fixedSignalEvent">
      <xs:attribute name="source" type="aos:signal_source" use="required" />
    </xs:extension>
  </xs:complexContent>
</xs:complexType>

另一种解决方法是在基类型中添加attribute wildcard

<xs:complexType name="event" abstract="true" >
    <xs:attribute name="move" type="aos:move_ref" use="required" />
    <xs:attribute name="type" type="aos:event_type" use="required" />
    <xs:anyAttribute />
</xs:complexType>

这不是一个等价的解决方案,因为它允许事件为属性提供任何内容(一般来说,这可能是不受欢迎的,但可能不是代码生成),并且它不会添加其他类型(是可取的。

请注意,基础中的任何粒子(元素,组或通配符)必须为repeated in the restriction,否则元素中不允许使用它们。如果基础上需要受限属性,则限制中也必须使用该属性。限制必须满足许多其他属性才能成为有效的derivationparticle。规范不是那么可读,但你通常会偶然发现它。

另请参阅:“how to use restrictions and extensions in XSD simultanously”。