解析文本以创建XML

本文关键字:创建 XML 文本 | 更新日期: 2023-09-27 18:13:56

我从HttpWebRequest获得这样的字符串:

Student■John■Smith
■Subject1■10■10
■■Exam■A■B■C
■■Questions■B■A■C
■Subject2■223■227
Student■Ala■Cat 
■Subject3■101■102
■■Exam■A■B

我需要从它生成这样的XML(将它反序列化为对象):

 <student name="John" surname="Smith">
   <Subject1>
   <degrees>
    <degree>10</degree>
    <degree>10</degree>
    <degree special="Exam">A</degree>
    <degree special="Exam">B</degree>
    <degree special="Exam">C</degree>
    <degree special="Questions">A</degree>
    <degree special="Questions">b</degree>
    <degree special="Questions">c</degree>
   </degrees>
   </Subject1>
   <Subject2>
   <degrees>
     <degree>10</degree>
     <degree>10</degree>
   </Student>
   <Student name="Ala" surname="Cat">
   <Subject3>
   <degrees>
    <degree>101</degree>
    <degree>102</degree>
    <degrre special="Exam">A</degree>
    <degree special="Exam">B</degree>
   </degrees>
   </Subject3>
 </student>

有什么办法做到这一点,除了使用正则表达式?或者可能有另一种方法将它(原始响应)序列化到对象?

响应模型为:

Student ■ Student Name ■ Student Surname (*)
■ Class Name ■ Degree ■ Degree ■ Degree ... (*)
■■ Special Degree ■ Degree ■ Degree ■ Degree ... (*)
* - line can exist 0 or more time in a row

解析文本以创建XML

只是让你开始,不是一个完整的答案:

char sep = '■';  //whatever. copy/paste with care. 
XElement lastStudent = null, lastDegrees = null;
foreach (var line in lineCollection)
{
    string[] parts = line.Split(sep);
    int leading = parts.TakeWhile(s => s == "").Count();
    if (leading == 0)  // Student
    {
        // todo: validate parts.length, part[0]
        lastStudent = new XElement("Student",
            new XAttribute("name", parts[1]),
            new XAttribute("surname", parts[2]));
        doc.Root.Add(lastStudent);            
    }
    else if (leading == 1)  // Subject
    {
        // todo: validate 
        lastDegrees = new XElement("degrees",
                 parts.Skip(2).Select(p => new XElement("degree", p)) );
        lastStudent.Add(new XElement(parts[1], lastDegrees);               
    }
    else ...
}