Remove all text nodes from XML file

点点圈 提交于 2019-12-12 05:16:31

问题


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

Example Input:

<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> 

Expected Output:

<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> 

回答1:


How about:

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

EDIT: 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");



回答2:


This question should help: Linq to XML - update/alter the nodes of an XML Document

You can use Linq to open the document and alter the values or remove the nodes altogether.



来源:https://stackoverflow.com/questions/7756703/remove-all-text-nodes-from-xml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!