如何删除特定元素而不删除其子元素或C#中的数据?

如何删除特定元素而不删除其子元素或C#中的数据?,c#,.net,xml,linq,C#,.net,Xml,Linq,我有一个XML文件,其中包含多个标记。有些特定元素不需要标记,但需要值或其子节点 例如: <p><b>This is a value</b></p> <h2><b><i>This is another value</i></b></h2> <h3><b>This is the last value</b></h3> 这是一个值

我有一个XML文件,其中包含多个
标记。有些特定元素不需要标记,但需要值或其子节点

例如:

<p><b>This is a value</b></p>
<h2><b><i>This is another value</i></b></h2>
<h3><b>This is the last value</b></h3>
这是一个值

这是另一个价值 这是最后一个值
在这里,对于
来说,这很酷,不需要删除任何内容。但是对于
,我希望删除
标记。因此,最终值将为:

<p><b>This is a value</b></p>
<h2><i>This is another value</i></h2>
<h3>This is the last value</h3>
这是一个值

这是另一个价值 这是最后一个值

我知道我可以删除
标记,将其值保存在变量中,然后再次将其粘贴到元素中。但是还有其他的方法吗?我正在寻找
linq

尝试使用此功能:

    string RemoveTags(string file, string tagToRemove, string parentTag)
    {
        XDocument doc = XDocument.Parse(file);
        var remove = doc.Descendants().Where(el => el.Name == tagToRemove && el.Parent.Name == parentTag);
        for (int i = 0; i < remove.Count(); i++)
        {
            remove.ElementAt(i).Parent.Value = remove.ElementAt(i).Value;
        }

        return doc.ToString();
    }
输入:

<?xml version="1.0" encoding="utf-8"?>
<frame>
  <p>
    <b>This is a value</b>
  </p>
  <h2>
    <b>
      <i>This is another value</i>
    </b>
  </h2>
  <h3>
    <b>This is the last value</b>
  </h3>
</frame>


这是一个价值观

这是另一个价值 这是最后一个值
输出:

<?xml version="1.0" encoding="utf-8"?>
<frame>
  <p>
    <b>This is a value</b>
  </p>
  <h2>This is another value</h2>
  <h3>
    <b>This is the last value</b>
  </h3>
</frame>


这是一个价值观

这是另一个价值 这是最后一个值
xmlContent.Replace(“,string.Empty).Replace(“,string.Empty)
?这将删除所有的/tag,而不仅仅是他想要的@vasily。sib@Primo你希望有什么逻辑?关于何时删除标记以及何时保留标记的规则并不清楚。@DenisSchaf这只是一个提示,而不是答案。您可以使用
xmlContent.Replace(“,”).Replace(“,”)
同样的方法。取决于
xmlContent
的多样性。@denischaf和@vasily.sib-我想要像这样的
xdoc.substands()。其中(el=>el.Name==“h2”和&el.Elements(“b”).Count()>0)//删除标记,但保留其值。
。我的
XML
内容在字符串变量中,这需要一个文件,有没有办法给出变量并进行更改?我正在分析我的变量
xdoc=XDocument.Parse(filecontent,LoadOptions.PreserveWhitespace)我编辑了我的答案,现在它需要一个带有xml的字符串,而不是它所使用的路径。我不知道为什么,但它正在将最后一个元素与下一个元素合并。我的意思是
这是
一个
值。

这是另一个值。

正在变成
这是一个值。这是另一个值。


<?xml version="1.0" encoding="utf-8"?>
<frame>
  <p>
    <b>This is a value</b>
  </p>
  <h2>This is another value</h2>
  <h3>
    <b>This is the last value</b>
  </h3>
</frame>