【问题标题】:Unserialize an xml fragment as a string将 xml 片段反序列化为字符串
【发布时间】:2016-04-13 11:58:22
【问题描述】:

我有一个具有以下结构的 xml 文件

<claims id="claims01" lang="en">
    <claim id="c-en-01-0001" num="0001">
        <claim-text>bla bla:
            <claim-text>- one,</claim-text>
            <claim-text>- two,</claim-text>
            and also:
            <claim-text>- three,</claim-text>
            <claim-text>- four,</claim-text>
            <claim-text>- five.</claim-text>
        </claim-text>
    </claim>
    <!-- multiple claim -->
</claims>

我尝试使用具有以下类的 XmlSerializer 来反序列化声明集:

public class EPPDClaims {
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("lang")]
    public string Lang { get; set; }
    [XmlElement("claim")]
    public List<EPPDClaim> Claims { get; set; }
}

public class EPPDClaim {
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("num")]
    public int Number { get; set; }

    [XmlAnyElement("claim-text")]
    public string Text { get; set; }
}

在EPPDClaim.Text中我希望得到

"<claim-text>bla bla:<claim-text>- one,</claim-text><claim-text>- two,</claim-text>and also:<claim-text>- three,</claim-text><claim-text>- four,</claim-text><claim-text>- five.</claim-text>&lt;/claim-text>"

我尝试:

  • XmlElement("claim-text")
  • XmlText()
  • XmlAnyElement("claim-text")

但什么也没做。

是否有一种简单的方法可以使用 XmlSerializer 处理这种反序列化,或者我必须转到 Text 属性的 IXmlSerializable 实现?

有关 DTD 的信息:

<!ELEMENT claim-text  (#PCDATA | claim-text | claim-ref | b | i | u | o | sup | sub | 
           smallcaps | br | pre | crossref | figref | img | chemistry | maths | 
           tables)* >

【问题讨论】:

  • 对于我通常使用的 xml 内部文本:[XmlText]

标签: c# .net xml


【解决方案1】:

尝试使用这个:(XmlNode 类型的 XmlAnyElement)

[System.Xml.Serialization.XmlRootAttribute("claims", Namespace = "", IsNullable = false)]
public class EPPDClaims
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("lang")]
    public string Lang { get; set; }
    [XmlElement("claim")]
    public List<EPPDClaim> Claims { get; set; }
}

public class EPPDClaim
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("num")]
    public int Number { get; set; }
    [XmlAnyElement("claim-text")]
    public XmlNode Text { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(EPPDClaims));
        var obj = (EPPDClaims)serializer.Deserialize(System.IO.File.OpenRead("test.xml"));
        string s = obj.Claims.First().Text.InnerXml;
    }
}

反序列化后,字符串s的内容为:

bla bla:
<claim-text>- one,</claim-text><claim-text>- two,</claim-text>
and also:
<claim-text>- three,</claim-text><claim-text>- four,</claim-text><claim-text>- five.</claim-text>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多