到目前为止,我在 linq 方面做得不太好,所以试图编写 Linq 查询来检查是否存在子主题节点,如果 code="111" && isDisplay="Y" 或不存在。我正在使用。第二种方法中的任何条件,但我仍然是不确定。
static void Main(string[] args)
{
XElement rootElement = XElement.Load("TestXML.xml");
int StyCode = 1;
var lv1s = from lv1 in rootElement.Descendants("Class")
where lv1.Attribute("Code").Value.Equals("001")
select (from ltd in lv1.Descendants("Subject")
where ltd.Attribute("Course").Value.Equals("Engish")
select GetChildFromSubject(StyCode, ltd)).FirstOrDefault();
}
private static bool GetChildFromSubject(int styCode, XElement subject)
{
if (styCode == 0)
return subject.Attribute("SpeciaGuest").Value.Equals("Y");
else
{
//Below is the main issue with and condition on attributes.
return subject.Attribute("AllTeachers").Value.Equals("Y") ||
subject.Elements("Topic").Attributes("Code")
.Any(x => x.Value.Equals("111")) && subject.Elements("Topic").Attributes("isDisplay")
.Any(y => y.Value.Equals("Y"));
}
}
下面是 XML 文件
<Class Code="002">
<Subject Course="Math" AllTeachers='Y' SpeciaGuest='N'>
<Topic Code="1" isDisplay="Y">LAW1</Topic>
<Topic Code="2" isDisplay="Y">
LAW2
</Topic>
<Topic Code="3" isDisplay="N">
LAW3
</Topic>
</Subject>
<Subject Course="Engish" AllTeachers='N' SpeciaGuest='Y'>
<Topic Code="111" isDisplay="Y">LAW1</Topic>
</Subject>
<Subject Course="History" AllTeachers='Y' SpeciaGuest='Y'></Subject>
</Class>