【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 @ 2022-11-04 14:11  宋桓公  阅读(172)  评论(0编辑  收藏  举报