gpt4 book ai didi

c# - 解析文本以创建 XML

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:48 28 4
gpt4 key购买 nike

我从 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>

除了使用 Regex 之外,还有什么方法可以做到这一点吗?或者也许有另一种方法可以将它(原始响应)序列化为对象?

响应模型是:

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

最佳答案

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

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 ...

}

关于c# - 解析文本以创建 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8037309/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com