C#XML反序列化。从节点读取所有内部文本到字符串属性

时间:2016-12-21 18:03:51

标签: c# xml deserialization

我目前正在尝试修改我的类,以便我模型上的text属性包含某个节点(text)节点的所有内部文本。

给我提出问题的xml示例是:

            <component>
                <section>
                    <title>Reason for Visit</title>
                    <text>
                        <content ID="ID3EZZKACA">No Reason for Visit was given.</content>
                    </text>
                </section>
            </component>

我的目标是让我的模型的text属性具有以下字符串:

"<content ID="ID0EAAKACA">No Reason for Visit was given.</content>"

目前我的模型如下所示:

public partial class ComponentSection {
    //other model properties here
    private string textField;

    [System.Xml.Serialization.XmlTextAttribute()]
  public string text {
        get {
            return this.textField;
        }
        set {
            this.textField = value;
        }
    }
    //getters/setters for other properties here
}

所以,我目前正试图通过使用注释[System.Xml.Serialization.XmlTextAttribute()]来实现这一点,但是当我这样做时,当反序列化xml时,text属性总是为null。

2 个答案:

答案 0 :(得分:4)

正如我在评论中所说,从序列化开始通常更容易。对于上面的XML,这里有一些类

public sealed class component
{
    public section section { get; set; }
}
public sealed class section
{
    public string title { get; set; }
    public text text { get; set; }
}
public sealed class text
{
    public content content { get; set; }
}
public sealed class content
{
    public string text { get; set; }
    public string ID { get; set; }
}

然后,将内容类修改为control XML serialization

public sealed class content
{
    [XmlText]
    public string text { get; set; }
    [XmlAttribute]
    public string ID { get; set; }
}

然后,您可以使用以下代码序列化实例:

        static string ToXmlString<T>(T t)
        {
            var serializer = new XmlSerializer(t.GetType());
            using (var sw = new System.IO.StringWriter())
            {
                serializer.Serialize(sw, t);
                return sw.ToString();
            }
        }
        static void Main(string[] args)
        {
            var c = new component { section = new section {
                            title = "Reason for Visit", text = new text { content = new content {
                            ID = "ID3EZZKACA", text = "No Reason for Visit was given." } } } };

            string s = ToXmlString(c);
            Console.WriteLine(s);
        }

结果是以下XML:

<?xml version="1.0" encoding="utf-16"?>
<component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http
://www.w3.org/2001/XMLSchema">
  <section>
    <title>Reason for Visit</title>
    <text>
      <content ID="ID3EZZKACA">No Reason for Visit was given.</content>
    </text>
  </section>
</component>

答案 1 :(得分:0)

使用XmlAnyElement属性并将text属性定义为XmlElement。

            [XmlAnyElement]
            public XmlElement text { get; set; }

这将导致text元素的内容加载到text属性中。