如何使用csharp删除xml中的节点 [英] How to delete node in xml using csharp

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

问题描述

我想从下面的XML中删除transactionID节点.我尝试使用doc.selectsinglenode(xpath)选择该节点.但这不起作用可能是由于XML中存在命名空间.
有什么解决方案可以从XML中删除上述节点?
XML在下面给出.

I want to remove transactionID node from the below XML.I tried to select the node using doc.selectsinglenode(xpath). But this is not working may be due to namespace present in the XML.
Is there any solution to delete the above mentioned node from the XML?
The XML is given below.

<?xml version="1.0" ?>
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
    <EnvelopeVersion>2.0</EnvelopeVersion>
    <Header>
        <MessageDetails>
            <Class>HMRC-VAT-DEC</Class>
            <Qualifier>poll</Qualifier>
            <Function>submit</Function>
            <TransactionID />
            <CorrelationID>1B93D48C02D740C6B79DE68A27F3ADE5</CorrelationID>
            <ResponseEndPoint




我使用的C#代码如下:




The C# code I used stands below:

XmlDocument doc=new XmlDocument();
doc.Load(fileName);

XmlNode node=doc.SelectSingleNode("//GovTalkMessage//EnvelopeVersion//Header//MessageDetails//Class//Qualifier//Function//TransactionID");
doc.DocumentElement.RemoveChild(node);

doc.Save(fileName);

推荐答案

在此处开始阅读有关XPath表达式的所有信息: http://www.w3schools.com/XPath/default.asp [ ^ ].

最好的问候,

Manfred
Start reading all about XPath expressions here: http://www.w3schools.com/XPath/default.asp[^].

Best Regards,

Manfred


首先,您是否尝试过调试?您提供了正确的路径"吗?
First of all have you tried debugging? Did you give the correct "path"?
XmlNode node=doc.SelectSingleNode("path");

在这里您可能找不到正确的节点.

但这里也是

here maybe you cant find the correct node.

But here also

doc.DocumentElement.RemoveChild(node); 


而不是尝试;


instead of this try;

node.Parent.RemoveChild(node);


您的Xpath是错误的,如果您从一开始就将它包含在问题中,我们可能会在几小时前发现:

Your Xpath is wrong which we could have found out hours ago if you had just included it in your question from the start:

XmlDocument doc=new XmlDocument();
doc.Load(fileName);
XmlNode node = doc.SelectSingleNode("/GovTalkMessage/Header/MessageDetails/TransactionID");
doc.DocumentElement.RemoveChild(node);
doc.Save(fileName);



请非常仔细地检查XML的结构,您将知道为什么我会像以前那样调整XPath.顺便说一下,XML示例的正确缩进肯定会帮助您认识它的结构!

祝您编码愉快!



Please review the structure of your XML very carefully and you will know why I adjusted your XPath the way I did. BTW proper indentation of your XML sample would surely help you in recognizing it''s structure!

Happy coding!


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

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