Search code examples
c#xsdlinq-to-xsd

Using named simple-types with LINQ to XSD results in compiler error


I have an XSD containing a simple type like this:

<xs:simpleType name="csharpName" id="csharpName">
    <xs:restriction base="xs:string">
        <xs:pattern value="[A-Za-z][A-Za-z0-9_]*" />
    </xs:restriction>
</xs:simpleType>

Now when I use this type:

 <xs:element name="typeName" type="csharpName" />

LINQ to XSD generates

this.SetElementWithValidation(XName.Get("typeName", ""), value, "typeName", global::.csharpName.TypeDefinition);`

Notice the ::. after global. Now that dot is very wrong there, I assume I'm missing a namespace. Now if I delete the dot manually it's working quite alright, but I'd rather not delete the dozen or so occurrences on every generation. Do you have any ideas?


Solution

  • Ok here's the real correct answer! (I'm using the nuget Linq2Xsd package)

    The questioners original solution has a big problem and that is that if you're adding your own namespace to an external XSD just to prevent this bug that when you try to generate XML you'll be sending that external service a made up namespace they can't recognize.

    • Start by removing any made up namespace and targetNamespace you may have added.
    • Then just add a file LINQ-TO-XSD-CONFIG.xsd to your project. It can be anywhere you want.
    • Set the Build Action to LinqToXsdConfiguration
    • NB: The file can be called whatever you want as long as it has this build action.

    enter image description here

    The contents of this file should be a list of all the namespaces and mappings to Clr types. Remember that every schema in a DLL gets compiled via the same \obj\Debug\LinqToXsdSource.cs file so you need to add each namespace for every XSD you're using in your project.

    The key here is the empty namespace where you put a default. This will avoid the ::. problem

    <?xml version="1.0" encoding="utf-8" ?>
    <Configuration xmlns="http://www.microsoft.com/xml/schema/linq">
      <Namespaces>
        <Namespace Schema="http://example.com/idr" Clr="example.com.idr"/>
        <Namespace Schema="" Clr="LinqXsdGenericNamespace"/>
      </Namespaces>
    </Configuration>
    

    See also : http://linqtoxsd.codeplex.com/discussions/238570