2011-02-28 132 views
0

我在XSD指定的默認值,如下所示:的LINQ to XML不返回默認值

<xs:complexType name="image"> 
    <xs:attribute name="path" type="xs:string" /> 
    <xs:attribute name="type" type="imageType" default="normal" /> 
</xs:complexType> 

但除非我明確地包括在XML值,「類型」總是返回一個空字符串當我運行一個LINQ查詢像這樣:

Dim images = From i In collection.<image> Select [email protected], [email protected] 

如果有這樣的預期還是可以省略屬性,讓LINQ檢查的默認值?

回答

0

那麼你首先驗證輸入XML與你的模式? 下面是一個例子:

Dim xrs As New XmlReaderSettings() 
xrs.Schemas.Add(Nothing, "..\..\XMLSchema1.xsd") 
xrs.ValidationType = ValidationType.Schema 

Dim doc As XDocument 

Using xr As XmlReader = XmlReader.Create("..\..\XMLFile1.xml", xrs) 
    doc = XDocument.Load(xr) 
End Using 

For Each img As XElement In doc.<images>.<image> 
    Console.WriteLine("Type: {0}", [email protected]) 
Next 

隨着架構是

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="images"> 
    <xs:complexType> 
     <xs:sequence maxOccurs="unbounded"> 
     <xs:element name="image"> 
      <xs:complexType> 
      <xs:attribute name="type" type="xs:string" default="normal"/> 
      </xs:complexType> 
     </xs:element> 
     </xs:sequence> 
    </xs:complexType> 
    </xs:element> 
</xs:schema> 

和XML輸入是

<images> 
    <image/> 
    <image type="vector"/> 
</images> 

該樣本輸出

Type: normal 
Type: vector 
+0

由於馬丁,當場!我想到LINQ會根據xsi:schemaLocation屬性指定的模式驗證XML – Phil 2011-02-28 12:24:28