I defined 3 classes:
public class PublishedPage
{
public string Action { get; private set; }
public string PageGuid { get; set; }
public List<string> SearchableProperties { get; set; }
public PublishedPage()
{
Action = "Published";
SearchableProperties = new List<string>();
}
}
public class DeletedPage
{
public string Action { get; private set; }
public string PageGuid { get; set; }
public DeletedPage()
{
Action = "Deleted";
}
}
public class MovedPage
{
public string Action { get; private set; }
public string PageGuid { get; set; }
public string OldParentGuid { get; set; }
public string NewParentGuid { get; set; }
public MovedPage()
{
Action = "Moved";
}
}
Somewhere in code I have something like this:
List<PublishedPage> publishedPages = GetPublishedPages();
List<MovedPage> movedPages = GetMovedPages();
List<DeletedPage> deletedPages = GetDeletedPages();
Now I want to create a XML file containing these 3 collections but don't know how.
XML should be like this:
<PublishedPages>
<PublishedPage>
<Action>Published</Action>
<PageGuid>.....</PageGuid>
<SearchableProperties>
<Name>Name 1</Name>
<Name>Name 2</Name>
</SearchablePeoperties>
</PublishedPage>
<PublishedPage>
...
<PublishedPage>
</PublishedPages>
<MovedPages>
...
</MovedPages>
<DeletedPages>
...
</DeletedPages>
Any help would be appreciated.
Thank you!
Even though the XmlSerializer is the easiest one, if you already know the schema you can do it with a bit of linq to xml too:
XElement element =
new XElement("PublishedPages",
(from page in publishedPages
select new XElement("PublishedPage",
new XElement("Action", page.Action),
new XElement("PageGuid",page.PageGuid),
new XElement("SearchableProperties",
(from property in page.SearchableProperties
select new XElement("Name",property)))
)
)
);
Serialization is fairly slow. performance -wise. A similar approach would be something like this:
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter) {Formatting = Formatting.Indented};
// Start document
xmltextWriter.WriteStartDocument();
xmltextWriter.WriteStartElement("ROOT");
foreach (PublishedPage page in publishedPages)
{
//Create a page element
xmltextWriter.WriteStartElement("Page");
xmltextWriter.WriteAttributeString("Action", page.Action);
xmltextWriter.WriteAttributeString("SearchableProperties", page.SearchableProperties);
xmltextWriter.WriteEndElement();
}
// Same for the other lists
// End document
xmltextWriter.WriteEndElement();
xmltextWriter.Flush();
xmltextWriter.Close();
stringWriter.Flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With