2011-01-14 64 views
1

出於某種原因,我不能完全得到nillable與.Net模式驗證程序正常工作。我試圖找到一種方法來使父節點可選,但同時防止空節點通過驗證器。模式驗證器「nillable」對於子節點不起作用?

下面是當前元素驗證:

<xs:element name="Dates" minOccurs="0" maxOccurs="1"> 
     <xs:complexType> 
     <xs:sequence> 
      <xs:element name="From" type="datetime" minOccurs="0" maxOccurs="1" /> 
      <xs:element name="To" type="datetime" minOccurs="0" maxOccurs="1" /> 
     </xs:sequence> 
     </xs:complexType> 
    </xs:element> 

我試圖改變日期元素的nillable =「假」,但不工作 - 空節點仍然使得過去驗證器。

我也嘗試將所有三個元素節點更改爲nillable =「false」 - 對於檢測空父節點而言工作正常但導致兩個子節點都成爲必需節點而不是保留可選節點。

所以我在這裏錯過了什麼?是的,我總是可以拋出一些代碼並使其工作......但我敢打賭,模式聲明中有一個變體,它會給我所需要的東西。

回答

1

你的情況的解決方案是 「選擇題」:

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="root"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element name="Dates" minOccurs="0" maxOccurs="1"> 
        <xs:complexType> 
         <xs:choice minOccurs="1" maxOccurs="2"> 
          <xs:choice maxOccurs="1"> 
           <xs:element name="From" type="xs:dateTime" /> 
          </xs:choice> 
          <xs:choice maxOccurs="1"> 
           <xs:element name="To" type="xs:dateTime" /> 
          </xs:choice> 
         </xs:choice> 
        </xs:complexType> 
       </xs:element> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
</xs:schema> 

有效證件

<?xml version="1.0"?> 
<root> 
    <Dates> 
     <From>2010-01-20T12:34:45</From> 
     <To>2011-01-20T12:34:45</To> 
    </Dates> 
</root> 


<?xml version="1.0"?> 
<root> 
    <Dates> 
     <From>2010-01-20T12:34:45</From> 
    </Dates> 
</root> 


<?xml version="1.0"?> 
<root> 
    <Dates> 
     <To>2011-01-20T12:34:45</To> 
    </Dates> 
</root> 

無效文檔

<?xml version="1.0"?> 
<root> 
    <Dates/> 
</root> 

最簡單的方法

<xs:element name="Dates" minOccurs="0" maxOccurs="1"> 
    <xs:complexType> 
     <xs:sequence> 
      <xs:any minOccurs="1" maxOccurs="2" processContents="lax" /> 
     </xs:sequence> 
    </xs:complexType> 
</xs:element> 

如果你只執行<From /><To />的方法是使用一種特殊的命名空間。

+0

非常接近,我認爲,但您的第一個示例(使用From/To節點)驗證失敗(請參閱http://www.xmlforasp.net/SchemaValidator.aspx)。這看起來像它的正確方向,但是當我在模式validatator網站上弄亂你的模式時,我只是讓事情變得更糟。 :-) – jerhewet 2011-01-21 18:55:23