XML——SelectSingleNode 获取有命名空间的节点的值

前端之家收集整理的这篇文章主要介绍了XML——SelectSingleNode 获取有命名空间的节点的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. XML文件

<?xml version="1.0" encoding="utf-8"?>
<dataConfiguration>
  <xmlSerializerSection type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.Data,Version=1.1.0.0,Culture=neutral,PublicKeyToken=c47c1bfbe00161e3">
    <enterpriseLibrary.databaseSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" defaultInstance="Database Instance" xmlns="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/data">
      <databaseTypes>
        <databaseType name="sql Server" type="Microsoft.Practices.EnterpriseLibrary.Data.sql.sqlDatabase,PublicKeyToken=c47c1bfbe00161e3" />
      </databaseTypes>
      <instances>
        <instance name="Database Instance" type="sql Server" connectionString="sql Connection String" />
      </instances>
      <connectionStrings>
        <connectionString name="sql Connection String">
          <parameters>
            <parameter name="server" value="server\sqlServer2005" isSensitive="false" />
            <parameter name="database" value="db" isSensitive="false" />
            <parameter name="user id" value="user" isSensitive="false" />
            <parameter name="password" value="pwd" isSensitive="true" />
            <parameter name="integrated security" value="False" isSensitive="false" />
            <parameter name="connection timeout" value="3600" isSensitive="false" />
          </parameters>
        </connectionString>
      </connectionStrings>
    </enterpriseLibrary.databaseSettings>
  </xmlSerializerSection>
</dataConfiguration>

2. C#获取
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            Test();
            Console.Read();
        }

        static void Test()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(@"H:\download\dataconfiguration.config");

            XmlNamespaceManager xnm = new XmlNamespaceManager(xml.NaMetable);
            xnm.AddNamespace("ns","http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/data");
            
            string DataSourceXpath = "/dataConfiguration/xmlSerializerSection/ns:enterpriseLibrary.databaseSettings/ns:connectionStrings/ns:connectionString/ns:parameters/ns:parameter[@name='server']/@value";
            string server = xml.DocumentElement.SelectSingleNode(DataSourceXpath,xnm).Value;
            Console.WriteLine(server);
        }
    }
}


其中最需要注意的是从有命名空间的节点开始, 就要一直加命名空间的前缀了。

原文链接:https://www.f2er.com/xml/295975.html

猜你在找的XML相关文章