views:

199

answers:

3

I've used XSD.EXE to convert an XSD into an object. That works fine and I can Deserialize using XMLSerializer just fine, except that the subelements which are generated as arrays don't populate.

    private SubElements[] subelementsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("SubElement", IsNullable=false)]
    public SubElement[] SubElement {
        get {
            return this.subelementField;
        }
        set {
            this.subelementField = value;
        }
    }

Even though there is data in the XML it just doesn't populate it when I use the following code:

// Deserialize
var result = serializer.Deserialize(new StringReader(data.XMLText.ToString()));

The root elements all work fine, just not the sub elements of this type of XML data:

<RootNode Weight="205" Year="1995">
  <ParentNodeWhichWorksFine Contact="John Doe">
    <SubElement SomeAttribute="123">
      <Location>New York City</Location>
      <Team>New York Pizza</Team>
    </SubElement>
  </ParentNodeWhichWorksFine>
</RootNode>

Am I missing some hints or something else that XSD.EXE is not including?

+2  A: 

I assume the class within which you define property SubElement is the one corresponding to ParentNodeWhichWorksFine? If so, try this change:

[XmlElement("SubElement", IsNullable=false)]
public SubElement[] SubElement

Also, you say that you've generated this code using xsd.exe. What was the input in that case - an .xsd file? If so, can you post the relevant part of it, too?

Pavel Minaev
+1  A: 

The XmlArrayItemAttribute attribute specifies a name for the child nodes of the array element defined by the public member SubElements. So that sample xml doesn't conform to the xsd, if that's the exact generated class xsd.exe produced.

According to the generated class, the <SubElement> items should be contained in a parent <SubElements> node like this:

<RootNode Weight="205" Year="1995">
  <ParentNodeWhichWorksFine Contact="John Doe">
    <SubElements>
      <SubElement SomeAttribute="123">
        <Location>New York City</Location>
        <Team>New York Pizza</Team>
      </SubElement>
    </SubElements>
  </ParentNodeWhichWorksFine>
</RootNode>

If you have control over the schema, I think changing it so that it corresponds to the sample xml is preferable (no parent node, following Pavel's solution), since the parent array nodes are superfluous.

Jeff Sternal
Turned out that a tag was not being included in the source XML (SubElements). thanks alow.
Nissan Fan
+1  A: 

Looks like your SubElement array in your generated class is missing the [XmlArray] attribute.

It needs to look like this:

[System.Xml.Serialization.XmlArrayAttribute("SubElements")]
[System.Xml.Serialization.XmlArrayItemAttribute("SubElement", IsNullable=false)]
public SubElement[] SubElement {
}

Something is not quite right in your XSD file, I reckon.

Wim Hollebrandse