[英]Querying XML with LINQ using attribute
我到目前为止在linq中还不是很好,所以我尝试编写Linq查询来检查子主题节点是否存在,如果code =“ 111” && isDisplay =“ Y”不存在。我在.Second方法中使用任何条件,但我仍然对此不确定。
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>
根据您的评论:
万能:如果代码=“ 111” && isDisplay =“ Y”,我想检查主题节点是否存在
如果您尝试在code = 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.