【发布时间】:2016-07-20 04:15:33
【问题描述】:
程序员朋友们好。
我的团队领导给了我一个任务,我需要将 xml 文件转换为 html5
我不想使用 xslt,这就是为什么我要在 System.xml。
但我是 LINQ 和 c# 的新手
具体来说:我要做的是删除带有 TAGS 名称的元素。
这是我的 xml 文件
<Root>
<Paragraph>
<Tags>
Just some text
</Tags>
</Paragraph>
<AnotherTag>
<Paragraph>
<Tags>
Another Text
</Tags>
</Paragraph>
</AnotherTag>
</Root>
可能的输出是:
<Root>
<Paragraph>
Just some text
</Paragraph>
<AnotherTag>
<Paragraph>
Another Text
</Paragraph>
</AnotherTag>
</Root>
它的作用是删除标签,但其内容仍保留在其位置
这是我的 C# 代码:
XElement root = XElement.Load("myxml.xml");
IEnumerable<XElement> tagsToremove =
from el in root.Descendants("Tags")
select el;
foreach (XElement el in tagsToremove)
{
Console.WriteLine(el);
}
所以我只需要删除节点的代码。谢谢你。
【问题讨论】:
-
尝试:el.ReplaceWith(el.Value);
-
是的,我试过了。但如果我使用该代码,它会给我错误消息:对象引用未设置为对象的实例。并且光标在“in”
-
要删除的标签必须为空。我通常使用: List
tagsToremove = root.Descendants("Tags").ToList();