c#-将XML部分反序列化为对象

我有一些反序列化为业务对象的XML.我正在使用XmlSerializer.Deserialize这样做.但是,我希望XML中包含的XmlElement之一保留为XElement.

由于XElement不可序列化,因此无法直接完成(使用XmlElementAttribute).我还尝试将该元素序列化为字符串(分两步尝试获取XElement),但是由于错误而失败:

unexpected node type element.
readelementstring method can only be
called on elements with simple or
empty content

知道如何做到吗?

这是xml和我想要的结果对象的示例:

<Person name="Joe">
  <Hobbies>
    <Hobby name="Reading" .../>
    <Hobby name="Photography" .../>
  </Hobbies>
  <HomeAddress>
    ...
  </HomeAddress>
</Person>

宾语:

 public class Person
    {
      [XmlAttribute("Name")]
      public string Name {get; set;}
      ?????
      public XElement Hobbies {get; set;}
      [XmlElement("HomeAddress")]
      public Address HomeAddress {get; set;}
    }

无效的尝试:

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

解决方法:

为了避免像IXmlSerializable之类的东西的辛苦工作,您可以按照半隐藏的传递XmlElement属性的方式进行操作.但是请注意,这不能完全满足您的要求,因为您只能有一个根XElement值(根据您的示例,不能为两个);你需要一个清单来做到这一点…

using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
public class Person
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
    [XmlIgnore]
    public XElement Hobbies { get; set; }

    [XmlElement("Hobbies")]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public XmlElement HobbiesSerialized
    {
        get
        {
            XElement hobbies = Hobbies;
            if(hobbies == null) return null;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(hobbies.ToString());
            return doc.DocumentElement;
        }
        set
        {
            Hobbies = value == null ? null
                : XElement.Parse(value.OuterXml);
        }
    }
    [XmlElement("HomeAddress")]
    public Address HomeAddress { get; set; }
}

public class Address { }

static class Progmam
{
    static void Main()
    {
        var p = new Person { Hobbies = new XElement("xml", new XAttribute("hi","there")) };
        var ser = new XmlSerializer(p.GetType());
        ser.Serialize(Console.Out, p);
    }
}
上一篇:XML(2)——Linq To XML:写


下一篇:如何将XElement转换为XComment(C#)