5

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!

1
  • do you want to WRITE xml only or you want to be able to read it to the same object structure as well? Commented Oct 6, 2010 at 11:59

5 Answers 5

5

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)))
                      )
         )
     );
Sign up to request clarification or add additional context in comments.

1 Comment

It has other benefits as well - if you need your XML structured in a certain way and if xmlserializer is a too heavy canon for a small target:)
4

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();

Comments

0

Use serialization, a good example is here: http://support.microsoft.com/kb/815813

Comments

0

What you need is XML Serialization as indicated by @Kyndings. But I will give you some code snippets to help:

In order to serialize one object your code should be something similar to

string serializedPublishedPage = Serializer.SerializeObject(PublishedPage, typeof(PublishedPage));

To have all three in the same XML you create a function that generates a list of XMLElements :

private List<XmlElement> functionA ()
{
    XmlDocument doc = new XmlDocument();
    List<XmlElement> elementList = new List<XmlElement>();
    XmlElement element;
    string serializedPublishedPage = Serializer.SerializeObject(PublishedPage, typeof(PublishedPage));
    string serializedDeletedPage = Serializer.SerializeObject(DeletedPage, typeof(DeletedPage));
    string serializedMovedPage = Serializer.SerializeObject(MovedPage, typeof(MovedPage));
    doc.LoadXml(serializedDemographic);
    element = doc.DocumentElement;
    elementList.Add(element);
    return elementList;
}

And later use it:

XmlDocument xmlData = new XmlDocument();
XmlElement root = xmlData.CreateElement("WHATEVER");
XmlElement Element;
XmlNode Node;


XmlElement AuxElement;
XmlNode AuxNode;
foreach (XmlElement xmlElement in functionA())
{
  AuxNode= doc.ImportNode(xmlElement, true);
  AuxElement.AppendChild(node);
}
// Now you have your XML objects in AuxElement

Node = xmlData.ImportNode(AuxElement, true);
root.AppendChild(Node);

// you have your full XML in xmlData in xmlData.InnerXml 

Comments

0

Try this, I'm using Xml Serialization :

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Pages pages = new Pages();
            pages.PublishedPages.Add(
                new PublishedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                    SearchableProperties = new List<string>()
                    {
                        "Foo",
                        "Bar",
                    }
                });
            pages.PublishedPages.Add(
                new PublishedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                    SearchableProperties = new List<string>()
                    {
                    "Tic",
                    "Tac",
                    "Toe",
                    }
                });
            pages.DeletedPages.Add(
                new DeletedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                });
            pages.DeletedPages.Add(
                new DeletedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                });
            pages.MovedPages.Add(
                new MovedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                    OldParentGuid = Guid.NewGuid().ToString(),
                    NewParentGuid = Guid.NewGuid().ToString(),
                });
            pages.MovedPages.Add(
                new MovedPage()
                {
                    PageGuid = Guid.NewGuid().ToString(),
                    OldParentGuid = Guid.NewGuid().ToString(),
                    NewParentGuid = Guid.NewGuid().ToString(),
                });
            Console.WriteLine(SerializeObject(pages));
        }

        /// <summary>
        /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        private static string UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        /// <summary>
        /// Converts the String to UTF8 Byte array and is used in De serialization
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        private static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        /// <summary>
        /// From http://www.dotnetjohn.com/articles.aspx?articleid=173
        /// Method to convert a custom Object to XML string
        /// </summary>
        /// <param name="pObject">Object that is to be serialized to XML</param>
        /// <returns>XML string</returns>
        public static string SerializeObject(Object pObject)
        {
            try
            {
                string xmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(pObject.GetType());
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xmlTextWriter.Formatting = Formatting.Indented;

                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                xs.Serialize(xmlTextWriter, pObject, ns);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                xmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return xmlizedString;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                return null;
            }
        }
    }

    [XmlRoot(ElementName="Pages", Namespace="")]
    public class Pages
    {
        public List<PublishedPage> PublishedPages { get; set; }
        public List<MovedPage> MovedPages { get; set; }
        public List<DeletedPage> DeletedPages { get; set; }

        public Pages()
        {
            PublishedPages = new List<PublishedPage>();
            MovedPages = new List<MovedPage>();
            DeletedPages = new List<DeletedPage>();
        }
    }

    public class PublishedPage
    {
        public string Action { get; 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; set; }
        public string PageGuid { get; set; }

        public DeletedPage()
        {
            Action = "Deleted";
        }
    }

    public class MovedPage
    {
        public string Action { get; set; }
        public string PageGuid { get; set; }
        public string OldParentGuid { get; set; }
        public string NewParentGuid { get; set; }

        public MovedPage()
        {
            Action = "Moved";
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.