到目前为止,我在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>
根据您的评论:
Magnum:我想检查主题节点是否存在,如果代码="111"&&isDisplay="Y"
如果尝试在代码=111且 isDiaply=Y 的情况下返回 TOPIC 节点,则下面是一次性的 LINQ 查询:
List<XElement> subjects = template.Descendants("Subject")
.Elements("Topic")
.Where(elementNode => elementNode.Attribute("Code").Value == "111" && elementNode.Attribute("isDisplay").Value == "Y").ToList();