3

How to represent the structure of the following XML for its further deserialization into classes?

<HeadElement id="1">
    Text in HeadElement start
    <SubElement samp="0">
        Text in SubElement
    </SubElement>
    Continue text
 </HeadElement>

My current code looks like this:

[DataContract]
public class ClaimText
{
    [DataMember, XmlElement(ElementName = "claim-ref")]
    public ClaimRef claimref; // { get; private set; }
    public void setclaimref(ClaimRef claimref_)
    {
        this.claimref = claimref_;
    }

    [DataMember, XmlText()]
    public string txt; // { get; private set; }
    public void settxt(string txt_)
    {
        this.txt = txt_;
    }       

}

Given the following XML contents:

<claim id="CLM-00016" num="00016">
    <claim-text>16. The midgate assembly of <claim-ref idref="CLM-00015">claim 15</claim-ref>, further comprising a second ramp member connected to an opposite side of the midgate panel for selectively covering an opposite end of the pass-through aperture. </claim-text>
</claim>

I get the object in which the link to the "claim-ref" is present, but not the entire text: only the second part of it (", further comprising ..."). How to get the whole text?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Kseniya Tsk
  • 115
  • 1
  • 1
  • 6

1 Answers1

1

First of all you are mixing attributes for DataContractSerializer and XmlSerializer.

Ad rem: in case of mixed elements it's better to use XmlSerializer. Here is the structure that works with your XML:

[XmlRoot(ElementName = "claim")]
public class ClaimText
{
    [XmlAttribute]
    public string id;

    [XmlAttribute]
    public string num;

    [XmlElement(ElementName = "claim-text")]
    public ClaimInnerContents contents;
}

public class ClaimInnerContents
{
    [XmlElement(ElementName = "claim-ref", Type = typeof(ClaimRef))]
    [XmlText(Type = typeof(string))]
    public object[] contents;
}

public class ClaimRef
{
    [XmlAttribute]
    public string idref;

    [XmlText]
    public string text;
}

ClaimRef and splitted text sections are deserialized into contents array as objects.

You can (and should) of course provide statically typed and checked accessors to particular elements of this array.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130