2014-02-03 2 views
0

Я пытаюсь написать код для получения элемента из .config файл в этом формате:Доступ к элементам файла Unity (.config) через XElement

<?xml version="1.0" encoding="utf-8" ?> 
    <configuration> 
     <configSections> 
     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> 
     </configSections> 

     <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 

     <alias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /> 
     <alias alias="hierarchical" type="Microsoft.Practices.Unity.HierarchicalLifetimeManager, Microsoft.Practices.Unity" /> 
     <alias alias="session" type="Microsoft.Practices.Unity.SessionLifetimeManager, TelventDMS.Web.Common" /> 
     <alias alias="IReportService" type="Web.Common.Interfaces.IReportService, Web.Common" /> 
     <alias alias="ReportServiceImpl" type="Web.Common.Services.ReportServiceImpl`1, Web.Common" /> 
     <alias alias="TAReport" type="Web.WebClient.Areas.Reports.Services.TopologyAnalyzerServiceImpl, Web.WebClient" /> 
     <alias alias="TAReportJobParam" type="UI.ServiceProxies.TAReportJobParam, UI.ServiceProxies.ServiceProxies" /> 
     <alias alias="ViolationsReport" type="Web.WebClient.Areas.Reports.Services.ViolationsServiceImpl, Web.WebClient.TDMSWebApp" /> 
     <alias alias="ViolationsJobParam" type="UI.ServiceProxies.ViolationsJobParam, UI.ServiceProxies.ServiceProxies" /> 
     <assembly name="Web.WebClient.TDMSWebApp" /> 
     <container name="container"> 
      <register name="configService" type="Web.Common.Interfaces.IConfigService, Web.Common" 
      mapTo="Web.Common.Services.ConfigServiceImpl, Web.Common"> 
      <lifetime type="singleton" /> 
      <constructor> 
       <param name="res" value="Resources.ClientStrings"> </param> 
       <param name="configFile" value="webclient.config"> </param> 
      </constructor> 
      </register> 

      <register name="scaleCoefConfigService" type="Web.WebClient.Services.IScaleCoefConfigService, Web.WebClient.TDMSWebApp" 
         mapTo="Web.WebClient.Services.Implementations.ScaleCoefConfigServiceImpl, Web.WebClient.TDMSWebApp"> 
      <lifetime type="singleton" /> 
      <constructor> 
       <param name="configService"> 
       <dependency name="configService"/> 
       </param> 
      </constructor> 
     </register> 

     <register name="sessionService" type="Web.Common.Interfaces.ISessionService, Web.Common" 
     mapTo="Web.Common.Services.SessionServiceImpl, Web.Common"> 
     <lifetime type="singleton" /> 
     </register> 

     <register name="licenseManagerService" type="Web.Common.Interfaces.ILicenseManagementService, Web.Common" 
          mapTo="Web.Common.Services.LicenseManagementServiceImpl, Web.Common"> 
      <lifetime type="singleton" /> 
     </register> 
     </container> 
    </unity> 
    </configuration> 

После я получаю регистры я хочу поставить значения типы и МАПТО в разделенных списков регистрации с этим кодом:

private void ReadAdvancedConfigFile() 
{ 
    XElement root = null; 
    root = XElement.Load(new XmlTextReader(@"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config")); 

    if (root != null) 
    { 
     var registers = root.Element("unity").Element("container").Descendants("register"); 
     List<string> tipList = new List<string>(); 
     List<string> mapToList = new List<string>(); 

     if (registers.Count() > 0) 
     { 
     foreach (var reg in registers) 
     { 
      tipList.Add(root.Attribute("type").Value); 
      mapToList.Add(root.Attribute("mapTo").Value); 

     } 
     } 
    } 
} 

Но во время отладки я получаю NullReferenceException() в этой строке кода:

var registers = root.Element("unity").Element("container").Descendants("register"); 

Как будто .config не имеет некоторых элементов. Я проверил файловую структуру .config много раз, и я уверен, что это должно быть так, но все же все, что я пробовал, не сработало. Я всегда получал нулевое значение для «единства».

P.S. Я получаю копию файла .config в корневой переменной, так что это не проблема. Только так, как будто элементы корня не существуют или не могут быть найдены.

У кого-нибудь есть идея или как решить эту проблему?

ответ

0
XElement root = XElement.Load(new XmlTextReader(@"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config"); 

if(root != null) 
{ 
    XNamespace ns = "http://schemas.microsoft.com/practices/2010/unity"; 

    var registers = root 
     .Element(ns + "unity") 
     .Element(ns + "container") 
     .Descendants(ns + "register"); 

    var tipList = registers.Select(x => x.Attribute("type").Value); 
    var mapToList = registers.Select(x => x.Attribute("mapTo").Value); 
} 
+0

Нет, их нет на самом деле. Настоящий XML-файл был слишком большим и слишком грязным для форума, поэтому я написал короткую версию, чтобы показать структуру и иерархию. Эти точки в примере предположительно показывают, что между ними есть много элементов. –

+0

Ваш пример config анализируется без проблем, если вы удалите точки и запятые. Должна быть какая-то разница в вашем «реальном» файле, вызывающем проблему. Не видя этого, трудно помочь. – xinux

+0

Реальный XML-файл получает синтаксический анализ, я проверяю, что во время отладки в корневой переменной я получаю все от исходного файла. Проблема в другом месте. Я поставлю оригинальный xml-файл, но, к сожалению, мне придется это сделать позже, потому что я все еще новый участник, и у меня нет всех привилегий на форуме. –

Смежные вопросы