Francesco Umani
Francesco Umani

Reputation: 69

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;
    }

Upvotes: 1

Views: 3371

Answers (2)

sq33G
sq33G

Reputation: 3360

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); }
}

}

Upvotes: 1

Alexander Mavrinsky
Alexander Mavrinsky

Reputation: 465

Hm... it seems something wrong with your schema, I think type="sisrt:Corpo" shold be type="Corpo" (because it defined as <complexType name="Corpo">)?

Also, if EventoClinico and Corpo are defined in different .xsd files, you may need to use <xs:include schemaLocation="anotherfile.xsd" /> directive

Upvotes: 0

Related Questions