【问题标题】:unable to persist newly added tags in xml using LINQ无法使用 LINQ 在 xml 中保留新添加的标签
【发布时间】:2014-04-28 20:24:47
【问题描述】:

我有以下 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>

<!-- New XML document created with EditiX XML Editor (http://www.editix.com) at Tue Mar 18 22:41:05 IST 2014 
-->
<html xsi:NamespaceSchemaLocation="http://www.w3.org/1999/xhtml DM_Project.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <head>
        <title>title1</title>
    </head>
    <body>
        <fragment name="heading" id="heading1">
            <h1>Heading 1</h1>
        </fragment>
    </body>
</html>

我正在使用 LINQ 将另一个片段标记添加到我的 xml 文件中,即:

XDocument xdocument = XDocument.Load("C:\\Users\\Administrator\\Desktop\\DM_Project.xml");
var id = "heading3";
var name="heading";
var content = "This is the data part";
var temp = xdocument.Descendants("fragment").First();
temp.Parent.Add(new XElement("fragment", content, new XAttribute("id", id), new XAttribute("name", name)));
var temp1 = xdocument.Descendants("fragment");
Console.WriteLine(temp1);

查询的结果是:

<fragment name="heading" id="heading1">
  <h1>Heading 1</h1>
</fragment> 
<fragment id="heading3" name="heading">This is the data part</fragment> 

如果可以观察到一些 id 为“heading3”的片段标签,则添加。但是,如果尝试再次提取片段标签,请使用以下查询:

XDocument xdocument = XDocument.Load("C:\\Users\\Administrator\\Desktop\\DM_Project.xml");
var temp = xdocument.Descendants("fragment");
Console.WriteLine(temp);

结果是:

 <fragment name="heading" id="heading1">
      <h1>Heading 1</h1>
    </fragment>

新添加的标签丢失。如何使数据持久化?我在这里错过了什么吗?或者,整个方法本身就是错误的?

我正在使用 LINQPad 来测试我的查询。

谢谢。

【问题讨论】:

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


    【解决方案1】:

    您没有将文档保存回文件。完成编辑后调用XDocument.Save:

    string path = @"C:\Users\Administrator\Desktop\DM_Project.xml";
    XDocument xdocument = XDocument.Load(path);
    // modify document
    xdocument.Save(path);
    

    下次执行代码(即加载文档并查询它)时,新元素将会出现。

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2012-03-28
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多