<p>I'm working on a set of classes that will be used to serialize to XML.  The XML is not controlled by me and is organized rather well.  Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children.  Based on my current knowledge of XML Serialization, those nodes require another class.</p>

<p>Is there a way to make a class serialize to a set of XML nodes instead of just one.  Because I feel like I'm being as clear as mud, say we have the xml:</p>

<pre><code>&lt;root&gt;
    &lt;users&gt;
        &lt;user id=""&gt;
            &lt;firstname /&gt;
            &lt;lastname /&gt;
            ...
        &lt;/user&gt;
        &lt;user id=""&gt;
            &lt;firstname /&gt;
            &lt;lastname /&gt;
            ...
        &lt;/user&gt;
    &lt;/users&gt;
    &lt;groups&gt;
        &lt;group id="" groupname=""&gt;
            &lt;userid /&gt;
            &lt;userid /&gt;
        &lt;/group&gt;
        &lt;group id="" groupname=""&gt;
            &lt;userid /&gt;
            &lt;userid /&gt;
        &lt;/group&gt;
    &lt;/groups&gt;
&lt;/root&gt;
</code></pre>

<p>Ideally, 3 classes would be best.  A class <code>root</code> with collections of <code>user</code> and <code>group</code> objects.  However, best I can figure is that I need a class for <code>root</code>, <code>users</code>, <code>user</code>, <code>groups</code> and <code>group</code>, where <code>users</code> and <code>groups</code> contain only collections of <code>user</code> and <code>group</code> respectively, and <code>root</code> contains a <code>users</code>, and <code>groups</code> object.</p>

<p>Anyone out there who knows better than me?  (don't lie, I know there are).</p>

[{'answer_id': 76826, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 4, 'selected': True, 'text': '<p>Are you not using the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="nofollow noreferrer">XmlSerializer</a>? It\'s pretty damn good and makes doing things like this real easy (I use it quite a lot!).</p>\n\n<p>You can simply decorate your class properties with some attributes and the rest is all done for you..</p>\n\n<p>Have you considered using XmlSerializer or is there a particular reason why not?</p>\n\n<p>Heres a code snippet of all the work required to get the above to serialize (both ways):</p>\n\n<pre><code>[XmlArray("users"),\nXmlArrayItem("user")]\npublic List&lt;User&gt; Users\n{\n    get { return _users; }\n}\n</code></pre>\n'}, {'answer_id': 76868, 'author': 'paulwhit', 'author_id': 7301, 'author_profile': 'https://Stackoverflow.com/users/7301', 'pm_score': 0, 'selected': False, 'text': '<p>You would only need to have Users defined as an array of User objects. The XmlSerializer will render it appropriately for you.</p>\n\n<p>See this link for an example:\n<a href="http://www.informit.com/articles/article.aspx?p=23105&amp;seqNum=4" rel="nofollow noreferrer">http://www.informit.com/articles/article.aspx?p=23105&amp;seqNum=4</a></p>\n\n<p>Additionally, I would recommend using Visual Studio to generate an XSD and using the commandline utility XSD.EXE to spit out the class hierarchy for you, as per <a href="http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx" rel="nofollow noreferrer">http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDToCls.aspx</a></p>\n'}, {'answer_id': 77259, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I wrote this class up back in the day to do what I think, is similar to what you are trying to do. You would use methods of this class on objects that you wish to serialize to XML. For instance, given an employee...</p>\n\n<p>using Utilities;\nusing System.Xml.Serialization;</p>\n\n<p>[XmlRoot("Employee")]\npublic class Employee\n{\n     private String name = "Steve";</p>\n\n<pre><code> [XmlElement("Name")]\n public string Name { get { return name; } set{ name = value; } }\n\n public static void Main(String[] args)\n {\n      Employee e = new Employee();\n      XmlObjectSerializer.Save("c:\\steve.xml", e);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>this code should output:</p>\n\n<pre><code>&lt;Employee&gt;\n  &lt;Name&gt;Steve&lt;/Name&gt;\n&lt;/Employee&gt;\n</code></pre>\n\n<p>The object type (Employee) must be serializable. Try [Serializable(true)].\nI have a better version of this code someplace, I was just learning when I wrote it.\nAnyway, check out the code below. I\'m using it in some project, so it definitly works.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Xml.Serialization;\n\nnamespace Utilities\n{\n    /// &lt;summary&gt;\n    /// Opens and Saves objects to Xml\n    /// &lt;/summary&gt;\n    /// &lt;projectIndependent&gt;True&lt;/projectIndependent&gt;\n    public static class XmlObjectSerializer\n    {\n        /// &lt;summary&gt;\n        /// Serializes and saves data contained in obj to an XML file located at filePath &lt;para&gt;&lt;/para&gt;        \n        /// &lt;/summary&gt;\n        /// &lt;param name="filePath"&gt;The file path to save to&lt;/param&gt;\n        /// &lt;param name="obj"&gt;The object to save&lt;/param&gt;\n        /// &lt;exception cref="System.IO.IOException"&gt;Thrown if an error occurs while saving the object. See inner exception for details&lt;/exception&gt;\n        public static void Save(String filePath, Object obj)\n        {\n            // allows access to the file\n            StreamWriter oWriter =  null;\n\n            try\n            {\n                // Open a stream to the file path\n                 oWriter = new StreamWriter(filePath);\n\n                // Create a serializer for the object\'s type\n                XmlSerializer oSerializer = new XmlSerializer(obj.GetType());\n\n                // Serialize the object and write to the file\n                oSerializer.Serialize(oWriter.BaseStream, obj);\n            }\n            catch (Exception ex)\n            {\n                // throw any errors as IO exceptions\n                throw new IOException("An error occurred while saving the object", ex);\n            }\n            finally\n            {\n                // if a stream is open\n                if (oWriter != null)\n                {\n                    // close it\n                    oWriter.Close();\n                }\n            }\n        }\n\n        /// &lt;summary&gt;\n        /// Deserializes saved object data of type T in an XML file\n        /// located at filePath        \n        /// &lt;/summary&gt;\n        /// &lt;typeparam name="T"&gt;Type of object to deserialize&lt;/typeparam&gt;\n        /// &lt;param name="filePath"&gt;The path to open the object from&lt;/param&gt;\n        /// &lt;returns&gt;An object representing the file or the default value for type T&lt;/returns&gt;\n        /// &lt;exception cref="System.IO.IOException"&gt;Thrown if the file could not be opened. See inner exception for details&lt;/exception&gt;\n        public static T Open&lt;T&gt;(String filePath)\n        {\n            // gets access to the file\n            StreamReader oReader = null;\n\n            // the deserialized data\n            Object data;\n\n            try\n            {\n                // Open a stream to the file\n                oReader = new StreamReader(filePath);\n\n                // Create a deserializer for the object\'s type\n                XmlSerializer oDeserializer = new XmlSerializer(typeof(T));\n\n                // Deserialize the data and store it\n                data = oDeserializer.Deserialize(oReader.BaseStream);\n\n                //\n                // Return the deserialized object\n                // don\'t cast it if it\'s null\n                // will be null if open failed\n                //\n                if (data != null)\n                {\n                    return (T)data;\n                }\n                else\n                {\n                    return default(T);\n                }\n            }\n            catch (Exception ex)\n            {\n                // throw error\n                throw new IOException("An error occurred while opening the file", ex);\n            }\n            finally\n            {\n                // Close the stream\n                oReader.Close();\n            }\n        }\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/76793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13611/']