XDocument比XmlDocument好用太多。
比如,我需要解soap格式的XML:
- string xml_str = @"
- xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
- xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
-
-
-
-
admin -
0 - {""moid"":""WO09001"",""partID"":""3F258-A-MPWN"",""ppid"":""8789454645
- "",""testStation"":""T00001""}
-
888 -
GET_PROCESS_STATUS -
-
-
- ";
如果是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
它无视空间名称(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;
一次到位:
