首页 > 解决方案 > 如何创建和填充 xml 文件?

问题描述

我正在尝试使用信息创建和填充 xml 文件。我不确定该怎么做才能让它发挥作用。我有一个项目清单。该列表的类型为IEnumerable。这些物品属于我的班级MyItemMyItem里面有这些类型:

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

我能够创建一个xml文件。

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

但是我怎么能填写test.xml项目列表呢?

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

<MyFiles>
   <MyFile>
      <MyID> *Guid here* </MyID>
      <MyString> *String here* </MyString> 
   </MyFile>

   <MyFile>
      <MyID> *Guid2 here* </MyID>
      <MyString> *String2 here* </MyString> 
   </MyFile>
</MyFiles>

标签: c#xml

解决方案


您可以使用 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" );

推荐阅读