7

I'm having trouble figuring this out, I have an xml sheet that looks like this

<root>
  <list id="1" title="One">
    <word>TEST1</word>
    <word>TEST2</word>
    <word>TEST3</word>
    <word>TEST4</word>
    <word>TEST5</word>
    <word>TEST6</word>   
  </list>
  <list id="2" title="Two">
    <word>TEST1</word>
    <word>TEST2</word>
    <word>TEST3</word>
    <word>TEST4</word>
    <word>TEST5</word>
    <word>TEST6</word>   
  </list>
</root>

And I'm trying to serialize it into

public class Items
{
  [XmlAttribute("id")]
  public string ID { get; set; } 

  [XmlAttribute("title")]
  public string Title { get; set; }   

  //I don't know what to do for this
  [Xml... something]
  public list<string> Words { get; set; }   
}

//I don't this this is right either
[XmlRoot("root")]
public class Lists
{
  [XmlArray("list")]
  [XmlArrayItem("word")]
  public List<Items> Get { get; set; }
}

//Deserialize XML to Lists Class
using (Stream s = File.OpenRead("myfile.xml"))
{
   Lists myLists = (Lists) new XmlSerializer(typeof (Lists)).Deserialize(s);
}

I'm really new with XML and XML serializing, any help would be much appreciated

2
  • Use XmlArray for Words property Commented May 24, 2012 at 18:15
  • 1
    Just a point of note, if you're converting XML into objects, that's Deserializing. Converting objects to XML (or any other format that can be sent to a disk or network steam) is serializing. Commented May 24, 2012 at 18:35

2 Answers 2

8

It should work if you declare your classes as

public class Items
{
    [XmlAttribute("id")]
    public string ID { get; set; }

    [XmlAttribute("title")]
    public string Title { get; set; }

    [XmlElement("word")]
    public List<string> Words { get; set; }
}

[XmlRoot("root")]
public class Lists
{
    [XmlElement("list")]
    public List<Items> Get { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

3

If you just need to read your XML into an object structure, it might be easier to use XLINQ.

Define your class like so:

public class WordList
{
  public string ID { get; set; } 
  public string Title { get; set; }   
  public List<string> Words { get; set; }   
}

And then read the XML:

XDocument xDocument = XDocument.Load("myfile.xml");

List<WordList> wordLists =
(
    from listElement in xDocument.Root.Elements("list")
    select new WordList
    {
        ID = listElement.Attribute("id").Value,
        Title = listElement.Attribute("title").Value,
        Words = 
        (
            from wordElement in listElement.Elements("word")
            select wordElement.Value
        ).ToList()
    }
 ).ToList();

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.