无法从字符串 XML 中获取节点值
本文关键字:获取 节点 XML 字符串 | 更新日期: 2023-09-27 18:37:21
我正在尝试从存储在字符串XML中的XML加载特定值。但由于某种原因,节点没有被拾取。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<megaServiceResponse xmlns="http://www.asbcsda/ms">
<serviceDetails>
<site>
<siteAccountNumber>123</siteAccountNumber>
<serviceAddress>
<streetAddress>abc</streetAddress>
<city>Rockaway</city>
<state>NJ</state>
<zip>07866</zip>
</serviceAddress>
<line>
<lsn>279542</lsn>
<billcode>NCB02HW51C</billcode>
<siteAccountId>2230066</siteAccountId>
<backupParentLsn>0</backupParentLsn>
<dateConnected>2012-06-07 07:29:33.0</dateConnected>
<lineType>Dedicated Lines</lineType>
<orderType>ESA</orderType>
<primaryOrBackupLine>No Backup/Failover LSN</primaryOrBackupLine>
<mplsOrdered>false</mplsOrdered>
<ipSecOrdered>false</ipSecOrdered>
<failoverOrdered>false</failoverOrdered>
<dbuServiceOrdered>false</dbuServiceOrdered>
<lsnClli>DNVLNJRK</lsnClli>
<serviceProducts>
<serviceProduct>
<serviceType>Enhanced IP</serviceType>
<productName>/29 IP Address Block (5 useable)</productName>
<quantity>1</quantity>
</serviceProduct>
<serviceProduct>
<serviceType>Enterprise</serviceType>
<productName>T1 1.5 (ESA8)</productName>
<quantity>1</quantity>
</serviceProduct>
</serviceProducts>
</line>
</site>
</serviceDetails>
</megaServiceResponse>
我要获取的节点是/megaServiceResponse/serviceDetails/site/line/serviceProducts/serviceProduct
我正在使用以下代码
XmlDocument doc = new XmlDocument();
doc.LoadXml(json); //json is an XML string
var nodes = doc.SelectNodes("/megaServiceResponse/serviceDetails/site/line/serviceProducts/serviceProduct");
上面的行返回空节点。
这是因为
您在 XML 中有一个命名空间。因此,您要么删除它并使用您的代码,如下所示:
<megaServiceResponse>
<serviceDetails>
或者您需要在选择节点之前声明它,如下所示:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("mp", "http://www.abcdesg.com/ms");
var nodes = doc.SelectNodes("//mp:megaServiceResponse/mp:serviceDetails/mp:site/mp:line/mp:serviceProducts/mp:serviceProduct", nsmgr);