Ling to XML(Literals): implicit Type Conversion ?
-
Monday, November 03, 2008 8:03 PM
Hi,
i have a small problem with Linq to XML:
The following lines are written with VB 2008 / .Net 3.5Code SnippetOption Strict On
Imports http://mytarget.sample.com/linq2xml">
Imports System.Xml.Linq
Imports System.Xml
Imports System.LinqModule Module1
Sub Main()
Dim mytest = <?xml version="1.0" encoding="utf-8"?>
<myroot xmlns="http://mytarget.sample.com/linq2xml">
<Sample MyAttribute="12">This is a Test</Sample>
<numVal>12</numVal>
</myroot>Dim myAttr = From myxml In mytest.<myroot> _
Where myxml.<numVal>.Value = 12 ' this is the Error-Line
'Where myxml.<Sample>.@MyAttribute = 12End Sub
End Module
i get the error message "Option Strict On disallows implicit conversions from 'String' to 'Double'"
at "Where myxml.<numVal>.Value = 12". I get the same error in the line "Where myxml.<Sample>.@MyAttribute = 12".This is the generated XSD File
Code Snippet<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://mytarget.sample.com/linq2xml" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="myroot">
<xs:complexType>
<xs:sequence>
<xs:element name="Sample">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="MyAttribute" type="xs:unsignedByte" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="numVal" type="xs:unsignedByte" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>Intellisense works fine with this, but there is no implicit Type-Conversion from String to integer/unsignedByte.
best regards,
Andreas B
All Replies
-
Tuesday, November 04, 2008 12:19 PM
@attributeName is always a string. And the Value property (of XElement or XAttribute) is also always a string.
You can however cast an XElement itself to some CLR types respectively the VB.NET equivalent, for instance an Integer:
Code SnippetDim myAttr = From myxml In mytest.<myroot> _ Where CType(myxml.<numVal>(0), Integer) = 12See http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx for the conversions that are possible.
There is also an experimental XSD to LINQ project http://blogs.msdn.com/xmlteam/archive/2008/02/21/linq-to-xsd-alpha-0-2.aspx but that is not part of the .NET framework SDK.

