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;
            }
        }
    }
  • 相关阅读:
    9-3 deepsort在win10配置
    多目标跟踪MOT综述
    OpenCV 学习笔记(11)【OpenCV】光流场方法标出前景(运动)和背景(静止)
    25 读取配置文件
    25树莓派硬件信息
    24 目标识别MobileNet
    23 人脸识别
    24 Home Assistant
    23 打包软件
    22-1 web传输视频 Opencv+usb摄像头 树莓派+Flask实现视频流媒体WEB服务器
  • 原文地址:https://www.cnblogs.com/crsky/p/14081890.html
Copyright © 2011-2022 走看看