2015-02-11 78 views
2

我对XML:如何使用XML Schema扩展属性?

<Devices> 
    <Device name="Phone" number="123456789"/> 
    <Device name="Computer" ip="192.168.0.1"/> 
</Devices> 

,我想设置一个架构对于这一点,在那里我有“设备”,我可以声明一个设备,但如果该设备具有NAME =“手机”一数量已按要求进行声明,但如果设备名称=“电脑”,以及,需要只为“计算机”

是有办法做到这一点的IP,这可能吗?

+1

您可以直接命名元素''和''*,然后单独控制其内容模型,也可以使用XSD 1.1中的条件类型分配。 – kjhughes 2015-02-11 16:24:08

+0

我不知道,如果你正在服用这种正确的方法(除非你在XML的设计没有选择)。我认为,为电话和计算机定义单独的元素会更好。我甚至不知道是否可以根据属性的值更改属性的类型。 – 2015-02-11 18:31:36

回答

2

这将是XML模式

<xs:schema elementFormDefault="qualified" version="1.0" 
    targetNamespace="stackoverflow" xmlns:tns="stackoverflow" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"> 

    <xs:element name="Devices" type="tns:deviceListType" /> 

    <xs:complexType name="deviceListType"> 
     <xs:sequence> 
      <xs:element name="Device" type="tns:deviceType" maxOccurs="unbounded" /> 
     </xs:sequence> 
    </xs:complexType> 

    <xs:complexType name="deviceType"> 

    </xs:complexType> 

    <xs:complexType name="computerType"> 
     <xs:complexContent> 
      <xs:extension base="tns:deviceType"> 
       <xs:attribute name="name"> 
        <xs:simpleType> 
         <xs:restriction base="xs:string"> 
          <xs:enumeration value="Computer" /> 
         </xs:restriction> 
        </xs:simpleType> 
       </xs:attribute> 
       <xs:attribute name="ip" /> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 

    <xs:complexType name="phoneType"> 
     <xs:complexContent> 
      <xs:extension base="tns:deviceType"> 
       <xs:attribute name="name"> 
        <xs:simpleType> 
         <xs:restriction base="xs:string"> 
          <xs:enumeration value="Phone" /> 
         </xs:restriction> 
        </xs:simpleType> 
       </xs:attribute> 
       <xs:attribute name="number" /> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 
</xs:schema> 

,这将是一个示例XML文档

<sf:Devices xmlns:sf="stackoverflow" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="stackoverflow test.xsd"> 
    <sf:Device xsi:type="sf:computerType" name="Computer" ip="1"/> 
    <sf:Device xsi:type="sf:phoneType" name="Phone" number="2"/> 
</sf:Devices> 

很抱歉,如果原来的XSD样品混乱。

+0

抱歉,我有点新在这里,请你解释更多这样的回答? :d感谢 – 2015-02-11 17:12:50

+0

上述(未测试)样品背后的想法是使用XML可扩展性来创建子类2的设备类型的。 我更新了我测试今天下午XSD答案。 – 2015-02-11 19:09:12