c# - 如何创建和填充 xml 文件?
问题描述
我正在尝试使用信息创建和填充 xml 文件。我不确定该怎么做才能让它发挥作用。我有一个项目清单。该列表的类型为IEnumerable
。这些物品属于我的班级MyItem
。MyItem
里面有这些类型:
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>
解决方案
您可以使用 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" );
推荐阅读
- python - Python:如何为子类中的属性设置默认值
- typescript - 该方法在nestjs接口中看起来未定义的位置
- asp.net-mvc - Telerik Kendo Chart : 如何将图表绑定到字符串类型
- excel - 在单元格或框中插入日期以更改图表数据范围
- build - 获取当前从 BitBake 构建的软件包版本
- python - 调用函数时出现 NameError(寻找更简洁的代码编写方式)
- reactjs - 被 CORS 政策阻止
- google-chrome - 如何在浏览器中手动设置 Nginx 基本身份验证无效
- r - 在 R 中:逐行返回最大值和相应的列名
- javascript - 将 html 元素排成一行