views:

830

answers:

1

Could you guys give me an example how to read and write from/to xml like this:

<Foolist>
   <Foo name="A">
     <Child name="Child 1"/>
     <Child name="Child 2"/>
   </Foo> 
   <Foo name = "B"/>
   <Foo name = "C">
     <Child name="Child 1">
       <Grandchild name ="Little 1"/>
     </Child>
   </Foo>
<Foolist>
+2  A: 

Does the element name really change per level? If not, you can use a very simple class model and XmlSerializer. Implementing IXmlSerializable is... tricky; and error-prone. Avoid it unless you absolutely have to use it.

If the names are different but rigid, I'd just run it through xsd:

xsd example.xml
xsd example.xsd /classes

For an XmlSerializer without IXmlSerializable example (same names at each level):

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

[XmlRoot("Foolist")]
public class Record
{
    public Record(string name)
        : this()
    {
        Name = name;
    }
    public Record() { Children = new List<Record>(); }
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("Child")]
    public List<Record> Children { get; set; }
}

static class Program
{
    static void Main()
    {
        Record root = new Record {
            Children = {
                new Record("A") {
                    Children = {
                        new Record("Child 1"),
                        new Record("Child 2"),
                    }
                }, new Record("B"),
                new Record("C") {
                    Children = {
                        new Record("Child 1") {
                            Children = {
                                new Record("Little 1")
                            }
                        }
                    }
                }}
            };
        var ser = new XmlSerializer(typeof(Record));
        ser.Serialize(Console.Out, root);
    }
}
Marc Gravell
But if Record inherited from other class which members I don't want to serialize?
Ike
Then either mark the child members as [XmlIgnore]; or switch to DataContractSerializer and wave bye to control of the layout; or have a separate "DTO" set of classes. I expect that the DTO route is the best option.
Marc Gravell
I still thinking about using IXmlSerializable. the only problem that as I understood xmlreader is 'forward only' thing. And I can't find any example of (de)serialization not just flat xml file, but with some structure.
Ike
You can try googling some more examples of IXmlSerializable implementation, like http://paltman.com/2006/jul/03/ixmlserializable-a-persistable-example/. But implementing IXmlSerializable for a class like the one in your post is overkill. Also, don't forget you don't need to implement IXmlSerializable for *all* classes in your hierarchy - you can start with a plain XmlSerializer and then later implement IXmlSerializable for a specific child node only (if needed).
Groo