Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a tag nested within a text section of another tag?

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?

like image 490
Kseniya Tsk Avatar asked Jan 31 '26 17:01

Kseniya Tsk


1 Answers

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.

like image 135
BartoszKP Avatar answered Feb 03 '26 08:02

BartoszKP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!