所以我有這個 XML 檔案:
<student_update date="2022-04-17" program="PMM" checksum="20021621">
<transaction>
<program>PMM</program>
<student_no>10010800</student_no>
<course_no>*</course_no>
<registration_no>111</registration_no>
<type>2</type>
<grade>100</grade>
<notes>Update Grade Test</notes>
</transaction>
<transaction>
<program>PMM</program>
<student_no>10010821</student_no>
<course_no>M-50033</course_no>
<registration_no>*</registration_no>
<type>1</type>
<grade>*</grade>
<notes>Register Course Test</notes>
</transaction>
</student_update>
我正在嘗試對其運行查詢,其中結果集應僅包含型別元素為 1 且等級元素為“*”的事務元素,或者型別元素為 2 且等級元素介于 0 和 100 之間的事務元素。
到目前為止,我提出的查詢是這樣的:
XDocument xDocument = XDocument.Load(inputFileName);
XElement root = xDocument.Element("student_update");
IEnumerable<XElement> transactionElements = xDocument.Descendants().Where(x => x.Name == "transaction");
IEnumerable<XElement> gradeForCourseElement = numTypeElement.Where(x => Int32.Parse(x.Element("type").Value) == 1 && x.Element("grade").Value == "*" ||
Int32.Parse(x.Element("type").Value) == 2 && Int32.Parse(x.Element("grade").Value) <= 100);
但它似乎不喜歡我這樣做的方式。我正在尋找一些關于如何實作所要求的結果的建議。謝謝!
uj5u.com熱心網友回復:
不確定numTypeElement
您的示例中的變數是什么。但是假設我們想從檔案的根元素中查詢,下面的代碼應該可以作業。您可能錯過的主要事情是首先您必須獲取檔案的所有后代元素。
這部分int.Parse(_.Element("grade")?.Value) <= 100
必須寫得更仔細。
var xml = "%your xml goes here%";
using (var textReader = new StringReader(xml))
{
using (var xmlTextReader = new XmlTextReader(textReader))
{
var xDoc = XDocument.Load(xmlTextReader);
var result = xDoc.Descendants()
.Where(_ => _.Name.LocalName == "transaction"
&&
(
_.Element("type")?.Value == "1" && _.Element("grade")?.Value == "*"
||
_.Element("type")?.Value == "2" && int.Parse(_.Element("grade")?.Value) <= 100
)
)
.ToList();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458724.html
標籤:C# 。网 xml xml 解析 linq 到 xml
上一篇:僅顯示鍵的集合物件