[英]LINQ Modify XML document
我需要修改一個包含產品銷售的 XML 文件。 我試圖用 LINQ 做到這一點,但它不起作用。 我有以下文件
<SalesProducts>
<ProductSale>
<Sale type="Fixed">
<ProductId>22</ProductId>
<Value>50</Value>
</ProductSale>
<ProductSale>
<Sale type="Discount">
<ProductId>32</ProductId>
<Value>33</Value>
</Product>
</SalesProducts>
我想在產品 ID 等於 22 的項目之后添加另一個 ProductSale 項目。
我嘗試了以下查詢。
var elProd = docX.Element("SalesProducts").
Elements("ProductSale").
Where(e => ((string)e.Element("ProductId")) == "22");
elProd.AddAfterSelf(
new XElement("Sale", ""),
new XElement("Value", "43"),
new XElement("ProductId", "154")));
但這不起作用。 此外,我無法向 Sale 元素添加屬性。
任何幫助都受到高度贊賞。
elProd
是XElement
的集合。 這就是您不能使用elProd.AddAfterSelf
的原因,因為該方法是為XElement
而不是IEnumerable<XElement>.
由於您正在搜索特定的 Product,您可以使用Single()
(假設沒有重復的ProductID
)來確保只選擇所需的元素。
var elProd = docX.Element("SalesProducts")
.Elements("ProductSale")
.Single(e => ((string)e.Element("ProductId") == "22"));
或者
var elProd = docX.Descendants("ProductSale")
.Single(e => ((string)e.Element("ProductId") == "22"));
選擇所需元素后,您現在可以使用AddAfterSelf
添加新元素。 請注意,您需要創建一個XElement
ProductSale,並將 Sale/Value/ProductID 作為子項。
elProd.AddAfterSelf(new XElement("ProductSale",
new XElement("Sale", new XAttribute("type", "Type of sale")),
new XElement("Value", "43"),
new XElement("ProductId", "154")));
輸出樣本
<SalesProducts>
<ProductSale>
<Sale type="Fixed"></Sale>
<ProductId>22</ProductId>
<Value>50</Value>
</ProductSale>
<ProductSale>
<Sale type="Type of sale" />
<Value>43</Value>
<ProductId>154</ProductId>
</ProductSale>
<ProductSale>
<Sale type="Discount"></Sale>
<ProductId>32</ProductId>
<Value>33</Value>
</ProductSale>
</SalesProducts>
您可以使用First方法的重載:
var first = xml.Elements().First(n => n.Element("ProductId").Value == "22");
first.AddAfterSelf(XElement.Parse(@"<ProductSale><Sale type='Discount'/><Value>43</Value><ProductId>154</ProductId></ProductSale>"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.