【问题标题】:LINQ to XML doesn't return default valueLINQ to XML 不返回默认值
【发布时间】:2011-02-28 19:56:53
【问题描述】:

我在 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 检查默认值?

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    您是否首先根据您的架构验证输入 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
    

    【讨论】:

    • 谢谢马丁,当机立断!我认为 LINQ 会根据 xsi:schemaLocation 属性指定的模式验证 XML
    猜你喜欢
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多