如何使用serialize创建xml文件?

时间:2016-01-07 13:44:54

标签: c# serialization

我想要像这样创建xml文件:

<channel>
<title>tttt</title>
<link>tttt</link>
<description>tttt</description>
<language>EN</language>
<item>
   <title>t</title>
   <description>d</description>
   <link>ll</link>
   <pubDate>d</pubDate>
</item>
<item>
   <title>t</title>
   <description>d</description>
   <link>ll</link>
   <pubDate>d</pubDate>
</item>
// item count uncertain
</channel>

项目计数不确定。我的课程是:

[System.Serializable]
public class channel
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public string language { get; set; }
    public string webMaster { get; set; }
    public string lastBuildDate { get; set; }

    public List<item> listItem
    {
        get;
        set;
    }
}
[Serializable]
public class item
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string pubDate { get; set; }
    public string Link { get; set; }
}

当我使用代码序列化时:

XmlSerializer serializer = new XmlSerializer(typeof(channel));
channel listNR = new channel();
// I fill listNR 
serializer.Serialize(myxml, listNR);

我的XML文件名是&#39; myxml&#39; ,myxml:

<channel>
<title>tttt</title>
<link>tttt</link>
<description>tttt</description>
<language>Fa</language>
<listItem>
<item>
   <title>t</title>
   <description>d</description>
   <link>http://www.farsnews.com/13941016001290</link>
   <pubDate>d</pubDate>
</item>
<item>
   <title>t</title>
   <description>d</description>
   <link>http://www.farsnews.com/13941016001290</link>
   <pubDate>d</pubDate>
</item>
<item>
   <title>t</title>
   <description>d</description>
   <link>http://www.farsnews.com/13941016001290</link>
   <pubDate>d</pubDate>
</item>
</listItem>
</channel>

标签<listItem>出现myxml file.how会修复吗?我希望my <listItem>标记在myxml文件中不会出现。怎么做?

1 个答案:

答案 0 :(得分:1)

尝试

[System.Serializable]
public class channel
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public string language { get; set; }
    public string webMaster { get; set; }
    public string lastBuildDate { get; set; }

    [XmlElement("item")]
    public List<item> listItem
    {
        get;
        set;
    }
}
[Serializable]
public class item
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string pubDate { get; set; }
    public string Link { get; set; }
}