c# - 使用 C# 使用 Linq 更新 XML

标签 c# xml linq

我的 XML 文件结构

<items>
  <item>
    <itemID>1</itemID>
    <isGadget>True</isGadget>
    <name>Star Wars Figures</name>
    <text1>LukeSkywalker</text1>
  </item>
</items>

通过 ITEMID 从 XML 中读取数据

XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("data.xml"));
var items = from item in xmlDoc.Descendants("item")
            where item.Element("itemID").Value == itemID
            select new
            {
                itemID = item.Element("itemID").Value,
                isGadget = bool.Parse(item.Element("isGadget").Value),
                name = item.Element("name").Value,
                text1 = item.Element("text1").Value,
             }

foreach (var item in items)
{
     ....
}

如何通过itemID更新XML数据? 谢谢!

最佳答案

要更新您的 xml,请使用 SetElementValue XElement 的方法:

var items = from item in xmlDoc.Descendants("item")
    where item.Element("itemID").Value == itemID
    select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

编辑: 是的,我尝试了您的示例并将更新的数据保存到文件中。使用 Save method of the XDocument 保存更新的 xml ,这是我试过的代码:

string xml = @"<items>
           <item>
            <itemID>1</itemID>
            <isGadget>True</isGadget>
            <name>Star Wars Figures</name>
            <text1>LukeSkywalker</text1>
           </item>
        </items>";

XDocument xmlDoc = XDocument.Parse(xml);

var items = from item in xmlDoc.Descendants("item")
            where item.Element("itemID").Value == "1"
            select item;

foreach (XElement itemElement in items)
{
    itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

xmlDoc.Save("data.xml");

关于c# - 使用 C# 使用 Linq 更新 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1487653/

相关文章:

xml - XSLT - 测试多个兄弟节点,如果有任何兄弟节点与测试匹配,则返回 true

xml - SVG XML :space attribute issue

c# - 2个Linq查询可以并行运行吗?

c# - 绑定(bind)到多个窗口上的相同属性不起作用

C# 根据字符串进行多次计算

c# - 阵列克隆访问?

使用 RelaxNG 进行 XML 模式验证

c# - ToListAsync 抛出 'Value cannot be null.' 异常

c# - 如何使用 linq to entities 获取字符串数组或 JSON 格式的数据?

c# - Arduino 使用 USB 连接到 Mysql