0

我想创建一个允许以下 XML 的 XSD 架构。我想我什么都有,除了<subsegent>元素上的属性。有人可以提供一个示例 XSD 吗?我尝试过的一切都会产生错误。

<Segment>
    <Subsegment target="all">This is test 1</Subsegment>
    <Subsegment target="some">This is test 2</Subsegment>
</Segment>

更新

这是我尝试过的一个 XSD。我希望序列中的元素具有属性。我收到此错误:“此上下文不支持 'http://www.w3.org/2001/XMLSchema:attribute' 元素。” 从我的工具。

谢谢

<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:complexType name="Segment">
    <xsd:sequence>
        <xsd:element name="Subsegment" minOccurs="1" maxOccurs="unbounded" type="xsd:string">
            <xsd:attribute name="target" type="xsd:string" use="required" />
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>
</xsd:schema>
4

1 回答 1

3

架构......

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

  <xsd:element name="Segment">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Subsegment" minOccurs="1" maxOccurs="unbounded" type="SubsegmentType"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <xsd:complexType name="SubsegmentType">
    <xsd:simpleContent>
      <xsd:extension base="xsd:string">
        <xsd:attribute name="target" type="xsd:string"/>
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

</xsd:schema>

而使用 xmllint 的结果......

xmllint testfile.xml --schema Subsegment.xsd
<?xml version="1.0" encoding="UTF-8"?>
<Segment>
    <Subsegment target="all">This is test 1</Subsegment>
    <Subsegment target="some">This is test 2</Subsegment>
</Segment>
testfile.xml validates

让我们添加一些错误来验证...

使用未指定的元素

xmllint badtestfile.xml --schema Subsegment.xsd
<?xml version="1.0" encoding="UTF-8"?>
<Segment>
    <Something-Else/>
    <Subsegment target="all">This is test 1</Subsegment>
    <Subsegment target="some">This is test 2</Subsegment>
</Segment>
badtestfile.xml:3: element Something-Else: Schemas validity error : Element 'Something-Else': This element is not expected. Expected is ( Subsegment ).
badtestfile.xml fails to validate

使用无效属性

xmllint badtestfile.xml --schema Subsegment.xsd
<?xml version="1.0" encoding="UTF-8"?>
<Segment>
    <Subsegment mytarget="all">This is test 1</Subsegment>
    <Subsegment target="some">This is test 2</Subsegment>
</Segment>
badtestfile.xml:3: element Subsegment: Schemas validity error : Element 'Subsegment', attribute 'mytarget': The attribute 'mytarget' is not allowed.
badtestfile.xml fails to validate
于 2012-04-26T14:15:08.153 回答