• 【.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;
            }
        }
    }
  • 相关阅读:
    mac添加环境变量
    Flex 中文字体终极解决方案
    C# Label背景透明
    C# 字节数组和十六进制字符串之间转换的另类写法
    C# params 动态参数
    HttpFlexSession注册失败的怪问题
    sun.misc.BASE64Encoder找不到jar包的解决方法
    Eclipse jee 3.7常用插件安装手记
    GitHub安装缓慢甚至下载失败的解决办法
    subclipse解决JavaHL不可用的问题
  • 原文地址:https://www.cnblogs.com/crsky/p/14081890.html
Copyright © 2020-2023  润新知