The first step is to mark up your class with the relevant Xml...
attributes which control the sreialization and whether to have attributes or elements. Your requirement basically changes the case, and has properties of the main object as attributes and properties of all child Link
objects as elements:
[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
}
Then to serialize it use XmlSerializer.Serialize
there are many overloads taking varios places to output the result. For testing you can use the Console.Out
.
XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj);
You may want to add an empty namespace manager, which stops the ugly extra xmlns
attributes:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj,ns);
Output of the above using this example object:
var obj = new ProfileSite{
ProfileId=1,
SiteId=2,
Links = new[]{
new Link{OriginalUrl="www.google.com" },
new Link{OriginalUrl="www.foo.com" }
}};
is this:
<?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>
Finally, here's a working example for you to play around with: http://rextester.com/XCJHD55693