C# - XML - 将某个元素的内部xml视为字符串

时间:2011-09-23 21:16:45

标签: c# xml-serialization

我有以下XML:

<Plan>
<Error>0</Error>
<Description>1</Description>
<Document>
  <ObjectID>06098INF1761320</ObjectID>
  <ced>109340336</ced>
  <abstract>DAVID STEVENSON</abstract>
  <ced_a />
  <NAM_REC />
  <ced_ap2 />
</Document>
</Plan>

我用它反序列化它:

[XmlRoot("Plan")]
    public class EPlan
    {
        [XmlElement("Error")]
        public string Error { get; set; }

        [XmlElement("Description")]
        public string Description { get; set; }

        [XmlElement("Document")]
        public List<EDocument> Documents { get; set; }
    }

    public class EDocument
    {
        [XmlText]    
        public string Document { get; set; }   
    }

问题在于我希望元素“Document”将其内部XML包含为单个字符串,我的意思是,该对象应具有以下值:

obj.Error = "0";
obj.Description = "1";
obj.Documents[0].Document = "<ObjectID>06098INF1761320</ObjectID><ced>109340336</ced><abstract>DAVID STEVENSON</abstract><ced_a /><NAM_REC /><ced_ap2 />";

但我之前提到的方式仍然是检索NULL“Document”属性。

是否有可能实现我想要的行为?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:11)

XmlText需要一个文本节点,但你拥有的实际上是元素节点。我不知道是否有直接的方法可以做到这一点,但你可以有一个XmlAnyElement节点来收集反序列化的结果,然后你将它们合并在一个字符串中,如果这是你需要的,如图所示在下面的例子中。

    [XmlRoot("Plan")]
    public class EPlan
    {
        [XmlElement("Error")]
        public string Error { get; set; }

        [XmlElement("Description")]
        public string Description { get; set; }

        [XmlElement("Document")]
        public List<EDocument> Documents { get; set; }
    }

    [XmlType]
    public class EDocument
    {
        private string document;

        [XmlAnyElement]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public XmlElement[] DocumentNodes { get; set; }

        [XmlIgnore]
        public string Document
        {
            get
            {
                if (this.document == null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var node in this.DocumentNodes)
                    {
                        sb.Append(node.OuterXml);
                    }

                    this.document = sb.ToString();
                }

                return this.document;
            }
        }
    }

    static void Test()
    {
        string xml = @"<Plan>
  <Error>0</Error>
  <Description>1</Description>
  <Document>
    <ObjectID>06098INF1761320</ObjectID>
    <ced>109340336</ced>
    <abstract>DAVID STEVENSON</abstract>
    <ced_a />
    <NAM_REC />
    <ced_ap2 />
  </Document>
  <Document>
    <ObjectID>id2</ObjectID>
    <ced>ced2</ced>
    <abstract>abstract2</abstract>
    <ced_a />
    <NAM_REC />
    <ced_ap2 />
  </Document>
</Plan>";
        XmlSerializer xs = new XmlSerializer(typeof(EPlan));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        EPlan obj = xs.Deserialize(ms) as EPlan;
        Console.WriteLine(obj.Documents[0].Document);
    }