为什么我不能使用linq to xml删除标签名称

时间:2016-07-22 08:11:09

标签: c# xml linq

如果我要删除的标签名称没有子节点,我为什么不能删除标签名称并保留其值

这是xml文件

<p>
<li>
      <BibUnstructured>Some text</BibUnstructured>
    </li>
    <li>
      <BibUnstructured>another text</BibUnstructured>
    </li>
</p>

这必须是输出

<p>
<li>
      Some text
    </li>
    <li>
      another text
    </li>
</p>

这是我现在的代码

XElement rootBook = XElement.Load("try.xml");
            IEnumerable<XElement> Book =
                from el in rootBook.Descendants("BibUnstructured").ToList()
                select el;
            foreach (XElement el in Book)
            {
                if (el.HasElements)
                {
                    el.ReplaceWith(el.Elements());
                }
                Console.WriteLine(el);
            }
            Console.WriteLine(rootBook.ToString());

如果我删除if语句,则删除标记名称及其内容

3 个答案:

答案 0 :(得分:4)

您的BibUnstructured元素没有子元素,但确实有子节点(在本例中为文本节点)。试试这个:

foreach (var book in doc.Descendants("BibUnstructured").ToList())
{
    if (book.Nodes().Any())
    {
        book.ReplaceWith(book.Nodes());
    }
}

有关正常工作的演示,请参阅this fiddle

答案 1 :(得分:1)

Charles 已经解释了为什么它不起作用,或者你也可以这样做。

    XElement element = XElement.Load("try.xml");

    element.Descendants("li").ToList().ForEach(x=> {            
        var item = x.Element("BibUnstructured");

        if(item != null)
        {
            x.Add(item.Value);      
            item.Remove();
        } 
    });

选中此Demo

答案 2 :(得分:0)

您必须将父节点的值设置为要删除的子节点的值。 请尝试以下方法:

 XElement rootBook = XElement.Load("try.xml");
        IEnumerable<XElement> Book =
            from el in rootBook.Descendants("BibUnstructured").ToList()
            select el;
        foreach (XElement el in Book)
        {
            if (!el.HasElements)
            {
                XElement parent= el.Parent;
                string value=el.Value;
                el.Remove();
                parent.Value=value;
                Console.WriteLine(parent);
            }

        }
        Console.WriteLine(rootBook.ToString());

输出是:

<li>Some text</li>
<li>another text</li>
<p>
<li>Some text</li>
<li>another text</li>
</p>