如何创建和填充xml文件?

时间:2019-05-24 12:24:34

标签: c# xml

我正在尝试用信息创建并填充xml文件。我不确定该怎么做。我有项目清单。该列表的类型为SelectedItem。这些项目属于我的课程IEnumerableMyItem包含以下类型:

MyItem

我能够创建一个xml文件。

public class MyItem
   {
      public Guid MyID { get; set; }
      public String MyString { get; set; }
   }

但是我如何用项目列表填充 DirectoryInfo di = Directory.CreateDirectory(myPath); System.Xml.XmlDocument file = new System.Xml.XmlDocument(); using (FileStream fs = new FileStream(di.FullName + "\\test.xml", FileMode.Create)) { file.Save(fs); }

我想像这样填充我的xml文件:

test.xml

2 个答案:

答案 0 :(得分:0)

您可以使用XmlDocument类,然后根据需要附加元素,请参见示例:

    XmlDocument doc = new XmlDocument( );

    //(1) the xml declaration is recommended, but not mandatory
    XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
    XmlElement root = doc.DocumentElement;
    doc.InsertBefore( xmlDeclaration, root );

    //(2) string.Empty makes cleaner code
    XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
    doc.AppendChild( element1 );

    XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
    element1.AppendChild( element2 );

    XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
    XmlText text1 = doc.CreateTextNode( "text" );
    element3.AppendChild( text1 );
    element2.AppendChild( element3 );

    XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
    XmlText text2 = doc.CreateTextNode( "other text" );
    element4.AppendChild( text2 );
    element2.AppendChild( element4 );

    doc.Save( "D:\\document.xml" );

答案 1 :(得分:0)

使用XMLSerializer将对象序列化为xml

using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(typeof(MyItem));
        serializer.Serialize(writer, MyItem);
        writer.Flush();
    }