【问题标题】:Use a custom xml namespace prefix in type attribute在类型属性中使用自定义 xml 命名空间前缀
【发布时间】:2019-12-22 22:23:54
【问题描述】:

我想引入一个新的命名空间和前缀“扩展”hod:string 来自 xsd:string。然后在我的模式中我可以定义一个字符串元素:

<xsd:element name="Label" type="hod:string"/>

这样我可以将hod:string 类型的所有元素的maxLength 更改为例如80。如果该要求稍后更改为50,我可以简单地在一个地方更改hod:string 的定义。这就是我正在尝试的——我的 IDE 不喜欢第 15 行(“无法解析符号 hod:string”):

<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:hod="http://hod.com/2019/XMLSchema/hod"
       attributeFormDefault="unqualified" elementFormDefault="qualified">

  <xsd:simpleType name="hod:string">
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="80"/>
    </xsd:restriction>
  </xsd:simpleType>

  <xsd:complexType name="Object">
    <xsd:sequence>
      <xsd:element name="Label" type="hod:string"/>
      <xsd:element name="MateriaID" type="GUID"/>
  ...

我将所有 'hod:string' 更改为 'mystring' 以验证我的定义正确并且看起来很开心,但我希望尽可能使用前缀。 (也试图改变这一点:attributeFormDefault="qualified" 但它似乎没有任何区别)

【问题讨论】:

  • w3.org/TR/xmlschema11-1/#declare-datatype 表明simpleType 元素的name 属性必须是NCName,因此不允许使用name="hod:string"。如果要在特定命名空间中声明类型,请设置命名空间为 targetNamespacexs:import 的架构。
  • @MartinHonnen 我尝试了你所说的并且 IDE 很高兴,但是当我运行它时会抛出这个异常: System.Xml.Schema.XmlSchemaValidationException : Type 'hod.com/2019/XMLSchema/hod:string' is not declared.
  • @MartinHonnen 我搞定了。我认为导入会导致XDocument.Load 自动加载&lt;xsd:import&gt; 中引用的.xsd 文件。显然不是这样。我寻找了一个自动加载它的选项,但没有找到。为新文件调用 XmlSchemaSet::add 已修复它。

标签: xml xml-namespaces xsd-validation prefix xml-validation


【解决方案1】:

简单类型从xs:schema 元素上的targetNamespace 属性获取它们的命名空间。由于您的 xs:schema 元素没有 targetNamespace 您当前的元素/类型,包括您的自定义字符串类型,没有命名空间。

如果您希望将当前元素保留在无命名空间中,而仅将字符串类型命名为命名空间,则需要在具有不同 targetNamepsace 的新架构中定义类型,并将其导入此架构。例如:

hodtypes.xsd

<xsd:schema
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:hod="http://hod.com/2019/XMLSchema/hod"
       targetNamespace="http://hod.com/2019/XMLSchema/hod">

  <xsd:simpleType name="string">
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="80"/>
    </xsd:restriction>
  </xsd:simpleType>

</xsd:schema>

ma​​in.xsd

<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:hod="http://hod.com/2019/XMLSchema/hod"
       attributeFormDefault="unqualified" elementFormDefault="qualified">

  <xsd:import namespace="http://hod.com/2019/XMLSchema/hod" schemaLocation="hodtypes.xsd" />

  <xsd:complexType name="Object">
    <xsd:sequence>
      <xsd:element name="Label" type="hod:string"/>
      <xsd:element name="MateriaID" type="GUID"/>
      ...

【讨论】:

  • 谢谢你,成功了。我只需在验证之前将新架构添加到 XmlSchemaSet。
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多