LINQ to XML不返回默认值

时间:2011-02-28 10:31:33

标签: linq-to-xml

我在XSD中指定了默认值,如下所示:

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

但是除非我在XML中明确包含一个值,否则当我运行LINQ查询时,'type'总是以空字符串形式返回:

Dim images = From i In collection.<image> Select i.@path, i.@type

是否应该这样或者是否可以省略该属性并让LINQ检查默认值?

1 个答案:

答案 0 :(得分: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}", img.@type)
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