Update XAttribute Value where XAttribute Name = X

2019-03-19 05:16发布

问题:

I have the following code which creates an XML file with a bunch of order information. 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 are greatly appreciated.

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");

Here's what my XML file looks like:

<?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>

回答1:

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");


回答2:

First you need to search for the element that you want to update. If you find it, do the update. Just remember to save the XDocument back to the file when you're done.

XDocument doc = ...;
var jason = doc
    .Descendants("Order")
    .Where(order => order.Attribute("Id").Value == "jason") // find "jason"
    .SingleOrDefault();
if (jason != null) // if found,
{
    // update something
    jason.Attribute("Quantity").SetValue(20);
}
doc.Save(...); // save if necessary


回答3:

Since you created the XML file, you know the root element of the XML so you can use this code to get the particular element you want:

TaxonPath = XElement.Parse(xml as string);
txtSource.Text = FindGetElementValue(TaxonPath, TaxonPathElement.Source);

XElement FindGetElementValue(XElement tree,String elementname)
{
    return tree.Descendants(elementName).FirstOrDefault();
}

With this, you can get the element, check its value, and change it as you desire.