无法从字符串 XML 中获取节点值

Unable to fetch a node value from string XML

我正在尝试从存储在字符串 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);