Search code examples
c#serializationxsd.exeany

Xsd.exe Any Type to XmlElement conversion. How to fill generated property?


I've an XSD (It's a standard RFC xsd as defined in http://web.rete.toscana.it/eCompliance/portale/dispatcher?from=rfc&pathname=%2Fapps%2Ftsf%2Fdata%2FeCompliance%2FeCRepository%2Frfc%2F0098.06%2F98.6.zip) with an

<complexType name="EventoClinico">
    ...
    <sequence>
...
        <element name="Corpo" type="sisrt:Corpo" minOccurs="0" />
    </sequence>
        ...
</complexType>

and "Corpo" is

<complexType name="Corpo">
    <sequence>
        <any namespace="##any" processContents="lax" />
    </sequence>
</complexType>

the xsd.exe tool translate the Corpo Element in a

public XmlElement Corpo;

property.

The question is:

How can I fill the property with my custom class:

public class Example{

public string AString {get;set;}
}

How can I set EventoClinico.Corpo = new Example("a string");?

Many Regards.

Francesco.

Here is a solution as suggested in following posts :

public XmlElement Convert<TObj>(TObj obj) { 
        XmlSerializer s = new XmlSerializer(typeof(TObj)); 
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings= new XmlWriterSettings();
        //settings.ConformanceLevel=ConformanceLevel.Fragment;
        settings.OmitXmlDeclaration=true;
        XmlWriter w = XmlWriter.Create(sb, settings);
        s.Serialize(w, obj); 
        return ToXmlElement(sb.ToString());
    }

    public XmlElement ToXmlElement(string xml)
    {
        XmlDocumentFragment frag = new XmlDocument().CreateDocumentFragment();
        frag.InnerXml = xml;
        return frag.FirstChild as XmlElement;
    }

Solution

  • Since any is not of a strictly defined type, xsd.exe generates XmlElement for it.

    http://msdn.microsoft.com/en-us/library/2w8zbwa2(v=vs.80).aspx

    If you want to put values in there, you're going to need to use the Attributes and ChildNodes collections.

    You could have your test class inherit from XmlElement and use get and set of its properties to keep ChildNodes and Attributes in sync with your member data.

    public class Example : XmlElement {
    
    public string AString {
        get { return GetAttribute("astring"); }
    
        set { SetAttribute("astring", value); }
    }
    
    }