[英]Remove all text nodes from XML file
I want to remove all text nodes (but not any other type of node) from an XML file. 我想从XML文件中删除所有文本节点(但不能删除任何其他类型的节点)。 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>
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: 编辑:请注意,以上是在我意识到从
XText
派生的XCData
之前,它XCData
更简单:
var doc = XDocument.Load("test.xml");
doc.DescendantNodes()
.OfType<XText>()
.Remove();
doc.Save("clean.xml");
This question should help: Linq to XML - update/alter the nodes of an XML Document 这个问题应该有所帮助: Linq to XML-更新/更改XML文档的节点
You can use Linq to open the document and alter the values or remove the nodes altogether. 您可以使用Linq打开文档并更改值或完全删除节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.