代码之家  ›  专栏  ›  技术社区  ›  mackenir

如何将元素反序列化为XmlNode?

  •  10
  • mackenir  · 技术社区  · 16 年前

    在C#中使用Xml序列化时,我希望将输入Xml的一部分反序列化到XmlNode。

    所以,考虑到这个XML:

    <Thing Name="George">
      <Document>
        <subnode1/>
        <subnode2/>
      </Document>
    </Thing>
    

    如何获得将Document属性设置为Document元素的代码?

    using System;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    [Serializable]
    public class Thing
    {
      [XmlAttribute] public string Name {get;set;}
      public XmlNode Document { get; set; }
    }
    
    class Program
    {
      static void Main()
      {
        const string xml = @"
    <Thing Name=""George"">
      <Document>
        <subnode1/>
        <subnode2/>
      </Document>
    </Thing>";
        var s = new XmlSerializer(typeof(Thing));
        var thing = s.Deserialize(new StringReader(xml)) as Thing;
      }
    }
    

    但是,当我使用XmlSerializer将上面的XML反序列化为某个实例时,Document属性包含子元素“subnode1”,而不是“Document”元素。

    1 回复  |  直到 16 年前
        1
  •  10
  •   code4life    16 年前

    [Serializable]
    public class Thing
    {
        [XmlAttribute] 
        public string Name {get;set;}
    
        [XmlAnyElement]
        public XmlNode Document { get; set; }
    }
    

    这将有一个不幸的副作用,因为您将发现不仅仅是subnode1和subnode2(所有 空白 也要反序列化。。。呃),所以你需要过滤掉它们:

    class Program
    {
        static void Main()
        {
            const string xml = @"
    <Thing Name=""George"">
      <Document>
        <subnode1/>
        <subnode2/>
      </Document>
    </Thing>";
            var s = new XmlSerializer(typeof(Thing));
            var thing = s.Deserialize(new StringReader(xml)) as Thing; 
    
            foreach (XmlNode node in thing.Document)
            {
                // should filter to only subnode1 and subnode2.
                if (node.Name != "" && node.Name != "#whitespace")
                {
                  Console.WriteLine(node.Name);
                }
            }
    
            Console.ReadLine();
        }
    }
    

    希望这有帮助!