如何将类序列化为xml结构?

时间:2012-05-23 11:17:04

标签: c# xml serialization deserialization

如何将下面的类{0}序列化到下面的xml {1}。

因此,类名,属性名应与xml匹配。

{0}:

[Serializable]
public class ProfileSite
{
    [XmlAttribute("profileId")] 
    public int ProfileId { get; set; }

    [XmlAttribute("siteId")] 
    public int SiteId { get; set; }

    public Link[] Links { get; set; }

    public XElement Deserialize()
    {

    }
}

{1}:

<profileSite profileId="" siteId="">
    <links>
      <link>
        <originalUrl></originalUrl>
        <isCrawled></isCrawled>
        <isBroken></isBroken>
        <isHtmlPage></isHtmlPage>
        <firstAppearedLevel></firstAppearedLevel>
      </link>
    </links>
  </profileSite>

非常感谢,

2 个答案:

答案 0 :(得分:1)

[XmlRoot("profileSite")]
public class ProfileSite
{
    [XmlAttribute("profileId")] 
    public int ProfileId { get; set; }

    [XmlAttribute("siteId")] 
    public int SiteId { get; set; }

    [XmlArray("links"), XmlArrayItem("link")]    
    public Link[] Links { get; set; }
}

然后:

var ser = new XmlSerializer(typeof(ProfileSite));
var site = (ProfileSite) ser.Deserialize(source);

答案 1 :(得分:1)

第一步是使用相关的Xml...属性标记您的类,这些属性控制重新定义以及是否具有属性或元素。您的要求基本上会更改大小写,并将主对象的属性作为所有子Link个对象的属性和属性作为元素:

[XmlRoot("profileSite")]
public class ProfileSite
{
    [XmlAttribute("profileId")] 
    public int ProfileId { get; set; }

    [XmlAttribute("siteId")] 
    public int SiteId { get; set; }

    [XmlArray("links"), XmlArrayItem("link")]    
    public Link[] Links { get; set; }

}

public class Link
{
    [XmlElement("originalUrl")]
    public string OriginalUrl{get;set;}
    // You other props here much like the above
}

然后使用XmlSerializer.Serialize对其进行序列化,有很多overloads用于获取输出结果的varios位置。要进行测试,您可以使用Console.Out

XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj);

您可能想要添加一个空的命名空间管理器,它可以阻止丑陋的额外xmlns属性:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj,ns);

使用此示例对象输出上述内容:

var obj = new ProfileSite{
            ProfileId=1,
            SiteId=2,
            Links = new[]{ 
                new Link{OriginalUrl="www.google.com" },
                new Link{OriginalUrl="www.foo.com" }
            }};

就是这样:

<?xml version="1.0" encoding="utf-8"?>
<profileSite profileId="1" siteId="2">
  <links>
    <link>
      <originalUrl>www.google.com</originalUrl>
    </link>
    <link>
      <originalUrl>www.foo.com</originalUrl>
    </link>
  </links>
</profileSite>

最后,这是一个让你玩的例子:http://rextester.com/XCJHD55693