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

一次到位:

posted @   宋桓公  阅读(223)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2021-11-04 【wpf】Initialized 事件的使用
2020-11-04 Vagrant 创建的虚拟机 如何用xshell登陆(初步记录)
2013-11-04 Verilog中的有符号计算之认知补码
点击右上角即可分享
微信分享提示