LINQ 复杂的删除和搜索查询
本文关键字:搜索 查询 删除 复杂 LINQ | 更新日期: 2023-09-27 18:35:14
//假设我有以下XML文件。
<warehouse>
<cat id="computer">
<item>
<SN>1</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
<item>
<SN>22</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
</cat>
<cat id="Stationery">
<item>
<SN> 33 </SN>
<name>note books</name>
<quantity>250</quantity>
<description>Caterpiller</description>
<price>5 USD</price>
</item>
</cat>
<cat id="Furniture">
<item>
<SN> 1 </SN>
<name>dasd</name>
<quantity>asdasd</quantity>
<description>das</description>
<price>dasd</price>
</item>
<item>
<SN>44</SN>
<name>Toshiba</name>
<quantity>12</quantity>
<description>CPU: CORE I5 RAM: 3 GB HD: 512 GB</description>
<price>400 USD</price>
</item>
<item>
</cat>
</warehouse>
问题 1:我想使用 linq 删除<item>
元素及其子元素,其中 <cat id="computer">
和 <SN>
具有特定的值,例如 44。
问题 2:我想使用 TextBox 和 Literal1 进行查询,该查询返回特定<item>
及其子项的 . 此查询应位于 LINQ 中。
例如
XDocument xmlDoc = XDocument.Load(Server.MapPath("/XML/Cat1.xml"));
var persons = from person in xmlDoc.Descendants("item")
where person.Element("SN").Value.Equals(DropDownList1.Text)
select person;
persons.Remove();
foreach (XElement person in persons.ToList())
{
person.Remove();
}
试试这个:-
xmlDoc.Root.Descendants("cat").Where(x => x.Attribute("id").Value == "computer")
.Descendants("item").Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text)
.Remove();
xmlDoc.Save(@"YourXML.xml");
对于过滤,您可以替换您喜欢的特定位置的值。另外,我直接使用了Trim
,最好先在实际代码中检查空字符串。
问题2:-
var result = xmlDoc.Descendants("item")
.Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text);
关于问题一,我会使用方法语法做这样的事情:
doc.Descendants("cat")
.Where(x => String.Equals((string)x.Attribute("id"), "computer", StringComparison.OrdinalIgnoreCase))
.Elements("item")
.Where(x => (string)x.Element("SN") == "44")
.Remove();
基本上选择所有的猫元素并按属性 id = 计算机过滤。然后选择每个项目中的所有项目,并通过SN = 44进行筛选。