zoukankan      html  css  js  c++  java
  • 【.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;
            }
        }
    }
  • 相关阅读:
    【分治法】线性时间选择(转)
    【分治法】最接近点对问题(转)
    概率DP入门总结 16题(转)
    动态规划初探及什么是无后效性? (转)
    第15章DP(转)
    整数快速乘法/快速幂+矩阵快速幂+Strassen算法 (转)
    矩阵乘法的理解(转)
    算法导论第4章习题与思考题(转)
    Transaction Script模式
    注册服务
  • 原文地址:https://www.cnblogs.com/crsky/p/14081890.html
Copyright © 2011-2022 走看看