这里是我的 XML:
<?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>
我需要读取这些元素 (名称、 TotalLectures、 AttendedLectures),并将它们显示在 3 单独文本框中。但我无法实现的结果。
我正在使用 XMLTextReader,因为 Linq to XML、 XPath 和其他人看起来有点复杂。
这是最能接近 (使用计算器帮助的另一个问题):
XmlTextReader reader = new XmlTextReader("xmldata.xml");
reader.Read();
while (reader.Read())
{
if (reader.Name == "Name")
{
textBox1.Text = reader.ReadString();
}
if (reader.Name == "TotalLectures")
{
textBox2.Text = reader.ReadString();
}
if (reader.Name == "AttendedLectures")
{
textBox3.Text = reader.ReadString();
}
}
但这不正确显示的主题的详细信息。我真的需要去为我的项目这工作 !: S
我假定当用户选择一个主题,主题 id 存储在一个变量中说它 SubjectId
。然后你可以做以下与 linq 结合使用 XDocument:
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;
doc.Descendants("Name")
然后将返回所有元素与标记"名称",.FirstOrDefault(o => o.Value == SubjectId)
将筛选以前结果返回只有第一个元素有 Value
平等 SubjectId
,或返回 null (如果找到不匹配的元素,然后.Parent
将返回父元素--的前一个结果元素-在这种情况下主题标记名称标记-。所以 subjectNode
将包含用户所选主题主题标记。