更新XAttribute值,其中XAttribute名称= X [英] Update XAttribute Value where XAttribute Name = X
问题描述
我有以下的code创造了一堆订单信息的XML文件。而且我希望能够更新,而不是删除一切,再重新添加一切都在这个XML文件中的条目。
我知道我能做到这一点:
xElement.Attribute(属性)。价值=价值;
但是,这将改变使用相同的名称每个属性的属性保存。我怎么只能改变事物的价值,当输入的ID等于杰森,例如?我需要加载XML文件,遍历整个文件,直到它找到一个匹配,因为我想改变属性,然后改变它,然后再保存该文件?
任何帮助/建议大大AP preciated。
感谢您
这里是我的XML文件的样子:
的XElement的XElement;
的XElement =新的XElement(订单);
的XElement元=新的XElement(
订购,
新XAttribute(ID,CustomId)
新XAttribute(数量,数量),
新XAttribute(PARTNO,PARTNO)
新XAttribute(说明,说明)
新XAttribute(折扣,折扣)
新XAttribute(货物,货运),
新XAttribute(UnitValue,UnitValue)
新XAttribute(LineTotal,LineTotal)
);
xElement.Add(元);
xElement.Save(PARTNO +的.xml);
< XML版本=1.0编码=UTF-8&GT?;
<订单>
<订单ID =V45Y7B458B数量=2PARTNO =5VNB98描述=新的自定义项目说明折扣=2.00运费=2.90UnitValue =27.88LineTotal =25.09/>
<订单ID =杰森数量=2PARTNO =杰森描述=新的自定义项目说明折扣=2.00运费=2.90UnitValue =27.88LineTotal =25.09/>
< /订单>
事情是这样的:
VAR DOC = XDocument.Load(filename.xml中);
VAR元= doc.Descendants(订单)
。凡(ARG => arg.Attribute(ID)值==贾森)
。单();
。element.Attribute(数量)值=3;
doc.Save(filename.xml中);
I have the following code which creates an XML file with a bunch of order information. And I'd like to be able to update an entry in this XML file, instead of deleting everything and re-adding everything again.
I know I can do this:
xElement.Attribute(attribute).Value = value;
But that will change every attribute with the same name as attribute holds. How can I only change the value of something when the entry's Id equals "jason", for example? Would I need to Load the XML file, iterate over the entire file until it finds a match for the attribute I want to change, then change it, and then Save the file again?
Any help/suggestions is greatly appreciated.
Thank you
Here's what my XML file looks like:
XElement xElement;
xElement = new XElement("Orders");
XElement element = new XElement(
"Order",
new XAttribute("Id", CustomId),
new XAttribute("Quantity", Quantity),
new XAttribute("PartNo", PartNo),
new XAttribute("Description", Description),
new XAttribute("Discount", Discount),
new XAttribute("Freight", Freight),
new XAttribute("UnitValue", UnitValue),
new XAttribute("LineTotal", LineTotal)
);
xElement.Add(element);
xElement.Save(PartNo + ".xml");
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order Id="V45Y7B458B" Quantity="2" PartNo="5VNB98" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
<Order Id="jason" Quantity="2" PartNo="jason" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
</Orders>
Something like this:
var doc = XDocument.Load("FileName.xml");
var element = doc.Descendants("Order")
.Where(arg => arg.Attribute("Id").Value == "jason")
.Single();
element.Attribute("Quantity").Value = "3";
doc.Save("FileName.xml");
这篇关于更新XAttribute值,其中XAttribute名称= X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!