XML Unique

最近一直很忙,一直没有空写blog

最近XML用的比较多,本来我以为XML不能实现类似数据库唯一主键的用途,查了下资料,找到Key和Unique这两个关键字可以实现这样的功能;指定unique的selector xpath(具体选择的xpath)和field(比对的字段)

<xsd:element name="root" type="myList">
  <xsd:unique name="myId">
   <xsd:selector xpath="./a"/>
   <xsd:field xpath="@ida"/>
  </xsd:unique>
 </xsd:element>
 <xsd:complexType name="myList">
  <xsd:sequence>
   <xsd:element name="a" maxOccurs="unbounded">
    <xsd:complexType>
     <xsd:attribute name="ida" type="xsd:NCName"/>
    </xsd:complexType>
   </xsd:element>
  </xsd:sequence>
 </xsd:complexType>

可以看出关键就是在他的父亲里面通过xpath定位到需要unique的字段,也就是这里的 ./a 和字段@ida的组合

但是如果在schema 里面指定了namespace,如:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.upzone.net/MSNRobot"  targetNamespace="http://www.upzone.net/MSNRobot" elementFormDefault="qualified">
这里targetNamespace和xmlns一至,而且指定elementFormDefault=qualified

同样情况指定unique时候xpath这样写:
<xs:unique name="testUnique">
   <xs:selector xpath="./Test"/>
   <xs:field xpath="@id"/>
  </xs:unique>
但是  schema验证时候unique并没有起作用,后来怀疑是命名空间的问题
于是修改schema,添加了一个前缀pdb指向相同的命名空间,  xmlns:pdb="http://www.upzone.net/MSNRobot",
unique把相应的prefix加上去 unique就起作用了,注意field也要加上pdb前缀
<xs:unique name="testUnique">
   <xs:selector xpath="./pdb:Test"/>
   <xs:field xpath="@id"/>
  </xs:unique>
  <xs:unique name="cmdUnique">
   <xs:selector xpath="./pdb:Command"/>
   <xs:field xpath="pdb:Title"/>
  </xs:unique>

posted @ 2006-10-25 13:59  upzone  阅读(450)  评论(0编辑  收藏  举报