c# - 从文本文件中读取并将其写入 XML

标签 c# asp.net xml

我想读取文本文件并将其写入现有的 XML 文件。

文本文件格式为

01 John
02 Rachel
03 Parker

我希望 XML 文件的输出为:

<StudentID>01<StudentID>
<StudentName>John<StudentName>
<StudentID>02<StudentID>
<StudentName>Rachel<StudentName>
<StudentID>03<StudentID>
<StudentName>Parker<StudentName>

最佳答案

如果您需要,这是另一种快速方法:

将类(class)学生作为

class Student
{
    public string ID { get; set; }
    public string Name { get; set; }
}

那么下面的代码应该可以工作:

string[] lines = File.ReadAllLines("D:\\A.txt");
List<Student> list = new List<Student>();

foreach (string line in lines)
{
    string[] contents = line.Split(new char[] { ' ' });
    var student = new Student { ID = contents[0], Name = contents[1] };
    list.Add(student);
}  

using(FileStream fs = new FileStream("D:\\B.xml", FileMode.Create))
{
    new XmlSerializer(typeof(List<Student>)).Serialize(fs, list);
}

关于c# - 从文本文件中读取并将其写入 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21283310/

相关文章:

c# - 没有 xaml 的 PropertyGrid(扩展 WPF 工具包)中的多行字符串?

c# - 如何为 multipart/form-data 设置 Web API Controller

c# - 异步 CTP 错误 - 任务永远无法完成

asp.net - Designer.cs 文件自动创建错误

javascript - Asp.Net 的 Javascript 中的 Node.js 代码

python - 我怎么能在不使用魔数(Magic Number)的情况下说文件是 SVG?

xml - XSLT 外部文档查找

c# - 随机 SQL 连接问题。工作,然后不工作,然后工作,然后 BAM!永远不会再工作?

c# - 找不到 PInvoke DLL - BUG?

Android Studio 布局 : Trying to make button 50% width and 50% height,,中间有按钮