0

我如何将下面的类 {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>

非常感谢,

4

2 回答 2

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有许多重载占用不同的位置来输出结果。对于测试,您可以使用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

于 2012-05-23T11:37:51.967 回答
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);
于 2012-05-23T11:24:50.983 回答