C# 使用XMLTextReader将XML读入Windows窗体
以下是我的XML:C# 使用XMLTextReader将XML读入Windows窗体,c#,xml,winforms,visual-studio,C#,Xml,Winforms,Visual Studio,以下是我的XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!--This is an XML Generated File--> <Subjects> <Subject> <Name>CG</Name> <TotalLectures>25</TotalLectures> <AttendedLe
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--This is an XML Generated File-->
<Subjects>
<Subject>
<Name>CG</Name>
<TotalLectures>25</TotalLectures>
<AttendedLectures>20</AttendedLectures>
</Subject>
<Subject>
<Name>ISM</Name>
<TotalLectures>40</TotalLectures>
<AttendedLectures>37</AttendedLectures>
</Subject>
</Subjects>
但这并没有正确显示主题的细节。我真的需要让它为我的项目工作我假设当用户选择一个主题时,存储在变量中的主题id表示它
SubjectId
。然后,可以使用XDocument和LINQ执行以下操作:
var doc = XDocument.Load("xmldata.xml");
var subjectNode = doc.Descendants("Name").FirstOrDefault(o => o.Value == SubjectId).Parent;
textBox1.Text = subjectNode.Element("Name").Value;
textBox2.Text = subjectNode.Element("TotalLectures").Value;
textBox3.Text = subjectNode.Element("AttendedLectures").Value;
将返回标记为“Name”的所有元素,然后doc.子体(“Name”)
将过滤以前的结果,以仅返回具有.FirstOrDefault(o=>o.Value==SubjectId)
值的第一个元素
等于
,或者如果未找到匹配的元素,则返回null,然后SubjectId
将返回上一个结果元素的父元素-本例中的Subject标记-Name标记-。因此,.Parent
将包含用户所选主题的主题标签subjectNode
doc
返回到xml文件:doc.Save(“xmldata.xml”)代码>是的,我设法做到了。我完成了我的申请!非常感谢你!
var doc = XDocument.Load("xmldata.xml");
var subjectNode = doc.Descendants("Name").FirstOrDefault(o => o.Value == SubjectId).Parent;
textBox1.Text = subjectNode.Element("Name").Value;
textBox2.Text = subjectNode.Element("TotalLectures").Value;
textBox3.Text = subjectNode.Element("AttendedLectures").Value;