【问题标题】:How to deserialize a tag nested within a text section of another tag?如何反序列化嵌套在另一个标签的文本部分中的标签?
【发布时间】:2014-08-18 12:58:57
【问题描述】:

如何表示以下 XML 的结构以便进一步反序列化为类?

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

我当前的代码如下所示:

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

}

给定以下 XML 内容:

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

我得到了指向“claim-ref”链接的对象,但不是整个文本:只有它的第二部分(“,进一步包括......”)。如何获取全文?

【问题讨论】:

  • 虽然我一个字都看不懂,但这根本不是有效的XML。标签只能包含其他标签,而这里也包含纯文本...
  • @KonradKokosa 这是一个有效的 xml。

标签: c# xml xml-deserialization


【解决方案1】:

首先,您混合了DataContractSerializerXmlSerializer 的属性。

Ad rem:如果是混合元素,最好使用XmlSerializer。以下是适用于您的 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 和拆分的文本部分被反序列化为 contents 数组作为对象。

您当然可以(并且应该)为此数组的特定元素提供静态类型和检查的访问器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 2020-01-29
    相关资源
    最近更新 更多