7

私はこれを理解するのに苦労しています、私はこのようなxmlシートを持っています

<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>

そして私はそれをシリアル化しようとしています

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

私はXMLとXMLシリアル化に本当に慣れていないので、どんな助けでも大歓迎です

4

2 に答える 2

8

クラスを次のように宣言すると機能するはずです

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; }
}
于 2012-05-24T18:30:20.347 に答える
3

XML をオブジェクト構造に読み込む必要があるだけの場合は、XLINQ を使用する方が簡単かもしれません。

次のようにクラスを定義します。

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

次に、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();
于 2012-05-24T18:26:27.363 に答える