【问题标题】:Update XAttribute Value where XAttribute Name = X更新 XAttribute 值,其中 XAttribute Name = X
【发布时间】:2011-08-28 13:20:51
【问题描述】:

我有以下代码,它创建一个包含一堆订单信息的 XML 文件。我希望能够更新此 XML 文件中的条目,而不是删除所有内容并重新添加所有内容。

我知道我能做到:

xElement.Attribute(attribute).Value = value;

但这会改变每个与属性名称相同的属性。例如,当条目的 Id 等于“jason”时,我怎样才能只更改某些东西的值?我是否需要加载 XML 文件,遍历整个文件,直到找到我要更改的属性的匹配项,然后更改它,然后再次保存文件?

非常感谢任何帮助/建议。

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 文件的样子:

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

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:

    类似这样的:

    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】:

      首先,您需要搜索要更新的元素。如果找到了,请进行更新。完成后请记住将 XDocument 保存回文件。

      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】:

        由于您创建了 XML 文件,因此您知道 XML 的根元素,因此您可以使用此代码来获取您想要的特定元素:

        TaxonPath = XElement.Parse(xml as string);
        txtSource.Text = FindGetElementValue(TaxonPath, TaxonPathElement.Source);
        
        XElement FindGetElementValue(XElement tree,String elementname)
        {
            return tree.Descendants(elementName).FirstOrDefault();
        }
        

        有了这个,你可以得到元素,检查它的值,并根据你的需要改变它。

        【讨论】:

        • 嗯,我从来没有见过这样的事情。非常有趣的东西!谢谢@Vir,我会检查一下:)
        猜你喜欢
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        相关资源
        最近更新 更多