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;
            }
        }
    }
  • 相关阅读:
    spring 循环依赖问题
    spring data jpa 关键字 命名
    mongodb 添加字段并设置默认值
    java mongoTemplate的group统计
    java8 从对象集合中取出某个字段的集合
    springboot12-zuul
    springboot11-01-security入门
    springboot项目怎么部署到外部tomcat
    springboot10-springcloud-eureka 服务注册与发现,负载均衡客户端(ribbon,feign)调用
    UML
  • 原文地址:https://www.cnblogs.com/crsky/p/14081890.html
Copyright © 2011-2022 走看看