【C#】xml解析对比XDocument和XmlDocument

XDocument比XmlDocument好用太多

  • XmlDocument 位于 using System.Xml; 下
  • XmlDocument位于using System.Xml.Linq;下

XmlDocument

比如,我需要解soap格式的XML:

string xml_str = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
 <soap:Body>
 <UniRequest xmlns=""http://tempuri.org/"">
 <rb>
 <account>admin</account>
 <optype>0</optype>
<param>{""moid"":""WO09001"",""partID"":""3F258-A-MPWN"",""ppid"":""8789454645
"",""testStation"":""T00001""}</param>
 <password>888</password>
 <sericeName>GET_PROCESS_STATUS</sericeName>
 </rb>
 </UniRequest>
 </soap:Body>
</soap:Envelope>
";

如果是XmlDocument,直接解析是不行的,这种标签带了空间名称(soap:),直接解析会导致报错,你得这么写(添加命名空间):

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml_str);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");

XmlNode rootNode = xmlDoc.SelectSingleNode("//soap:Envelope", nsmgr);

而且,找内层节点,你得一层层的剥开,没办法一次到位。

这太low了,适应性太差,结构稍有变化,就会嗝屁。于是我找到了XDocument

XDocument

它无视空间名称(soap:)直接读就完了,而且能一次到位:

比如我想将上面字符串中的json取出来:

TextReader tr = new StringReader(xml_str);
XDocument doc = XDocument.Load(tr);
XElement xroot = doc.Root;//根节点
var nodes = xroot.Descendants().FirstOrDefault(a => a.Name.LocalName == "param").Value;

一次到位:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code bean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值