删除 XML 根下的特定节点?
我的 XML 如下;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
<diacritics_sensitive>1</diacritics_sensitive>
<expansion>
<sub>Internet Explorer</sub>
<sub>IE</sub>
<sub>IE5</sub>
</expansion>
<expansion>
<sub>run</sub>
<sub>jog</sub>
</expansion>
</thesaurus>
</XML>
我想从 XML 中删除“扩展”节点。去掉process后就是这样;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
</thesaurus>
</XML>
我的代码如下;
XDocument tseng = XDocument.Load("C:\\tseng.xml");
XElement root = tseng.Element("XML").Element("thesaurus");
root.Remove();
tseng.Save("C:\\tseng.xml");
我收到错误“对象引用未设置到对象的实例。”对于“root.Remove()”行。 如何从 XML 文件中删除“扩展”节点?谢谢。
My XML is below;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
<diacritics_sensitive>1</diacritics_sensitive>
<expansion>
<sub>Internet Explorer</sub>
<sub>IE</sub>
<sub>IE5</sub>
</expansion>
<expansion>
<sub>run</sub>
<sub>jog</sub>
</expansion>
</thesaurus>
</XML>
I want to remove the "expansion" nodes from the XML. After removing process, it would be like that;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
</thesaurus>
</XML>
My code is below;
XDocument tseng = XDocument.Load("C:\\tseng.xml");
XElement root = tseng.Element("XML").Element("thesaurus");
root.Remove();
tseng.Save("C:\\tseng.xml");
I got an error "Object reference not set to an instance of an object." for line "root.Remove()".
How can I remove the "expansion" nodes from XML file? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
仅删除
扩展
元素:将删除
同义词库
的所有子元素:Use:
Will remove only
expansion
elements:Will remove all children of
thesaurus
:就像
你从它的父节点中删除一个节点...
如果你只想删除扩展节点,那么基本上你会找到一个删除,直到同义词库中没有任何节点,或者返回它们的列表并循环从它们的扩展节点中删除它们家长同义词库。
Something like
You remove a node from it's parent...
if you want to remove just the expansion nodes, then basically you find a remove until tere aren't any in thesaurus, or return a list of them and loop through removing them from their parent thesaurus.
您没有成功,因为您的
同义词库
具有不同的命名空间。您需要指定 ti 才能使其正常工作。一般来说,您的代码有效。您唯一需要删除非根元素的子元素才能达到您需要的结果。
You have no success because your
thesaurus
have different namespace. You need to specify ti to get it works.In general your code valid. The only thing that you need to delete child elements not root to reach results you needed.