从XML文件中删除所有文本节点 [英] Remove all text nodes from XML file

查看:67
本文介绍了从XML文件中删除所有文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从XML文件中删除所有文本节点(但不能删除任何其他类型的节点).我该怎么办?

I want to remove all text nodes (but not any other type of node) from an XML file. How can I do this?

示例输入:

<root>
<slideshow id="1">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>A</ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image>hii</Image>
<ImageContent>this</ImageContent>
<Thumbnail>is</Thumbnail>
<ThumbnailContent>B</ThumbnailContent>
</slideshow>
</root> 

预期输出:

<root>
<slideshow id="1">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
<slideshow id="2">
<Image></Image>
<ImageContent></ImageContent>
<Thumbnail></Thumbnail>
<ThumbnailContent></ThumbnailContent>
</slideshow>
</root> 

推荐答案

怎么样:

var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
   .Where(x => x.NodeType == XmlNodeType.Text ||
               x.NodeType == XmlNodeType.CDATA)
   .Remove();
doc.Save("clean.xml");

请注意,以上是在我意识到 XCData XText 派生,从而变得更加简单:

Note that the above was before I realized that XCData derived from XText, leading to the simpler:

var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
   .OfType<XText>()
   .Remove();
doc.Save("clean.xml");

这篇关于从XML文件中删除所有文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆