C# LINQ修改XML文档
我需要修改一个包含产品销售的XML文件。 我试着用LINQ做这个,但是没有用。我有以下文件C# LINQ修改XML文档,c#,linq,C#,Linq,我需要修改一个包含产品销售的XML文件。 我试着用LINQ做这个,但是没有用。我有以下文件 <SalesProducts> <ProductSale> <Sale type="Fixed"> <ProductId>22</ProductId> <Value>50</Value> </ProductSale> <Product
<SalesProducts>
<ProductSale>
<Sale type="Fixed">
<ProductId>22</ProductId>
<Value>50</Value>
</ProductSale>
<ProductSale>
<Sale type="Discount">
<ProductId>32</ProductId>
<Value>33</Value>
</Product>
</SalesProducts>
但这不起作用。
此外,我无法将属性添加到Sale元素
非常感谢您的帮助。
elProd
是XElement
的集合。这就是您无法使用elProd.addafterelf
的原因,因为该方法是为XElement
而不是为IEnumerable定义的。
由于您正在搜索特定的产品,因此可以使用Single()
(假设没有重复的ProductID
)确保只选择所需的元素
var elProd = docX.Element("SalesProducts")
.Elements("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>
22
50
43
154
32
33
elProd
是XElement
的集合。这就是您无法使用elProd.addafterelf
的原因,因为该方法是为XElement
而不是为IEnumerable定义的。
由于您正在搜索特定的产品,因此可以使用Single()
(假设没有重复的ProductID
)确保只选择所需的元素
var elProd = docX.Element("SalesProducts")
.Elements("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>
22
50
43
154
32
33
您可以使用方法重载:
var first=xml.Elements().first(n=>n.Element(“ProductId”).Value==“22”);
first.AddAfterSelf(XElement.Parse(@“43154”);
您可以使用方法重载:
var first=xml.Elements().first(n=>n.Element(“ProductId”).Value==“22”);
first.AddAfterSelf(XElement.Parse(@“43154”);
您的预期输出是什么?请使用预期输出更新OP您的XML格式完全不正确。您的预期输出是什么?请使用预期输出更新OP您的XML格式完全不正确。