【.NET】使用 XmlDocument 查找带命名空间的节点

假设有以下XML文档:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <Login xmlns="http://tempuri.org/">
            <LoginResult>
                <ReturnData>
                    <Code>0</Code>
                </ReturnData>
            </LoginResult>
        </Login>
    </soap:Body>
</soap:Envelope>

注意看 <Login> 节点,使用了一个没有定义前缀的命名空间,需要做特殊处理才能读取到它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Xml_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
               xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
               xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
    <soap:Body>
        <Login xmlns=""http://tempuri.org/"">
            <LoginResult>
                <ReturnData>
                    <Code>0</Code>
                </ReturnData>
            </LoginResult>
        </Login>
    </soap:Body>
</soap:Envelope>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            nsmgr.AddNamespace("temp", "http://tempuri.org/");

            var node = doc.SelectSingleNode("/soap:Envelope/soap:Body/temp:Login/temp:LoginResult/temp:ReturnData/temp:Code", nsmgr);
            var code = node.InnerText;
        }
    }
}
原文地址:https://www.cnblogs.com/crsky/p/14081890.html