How can I get attribute from subsection webconfig

2019-09-03 12:03发布

问题:

I try to get all attibutes from one subsection, but section have many subsection and the aplication didn't recognize, how can I do? this is my webconfig:

<configSections>
    <section name="Seccion" type="ManejoConfiguracion.SeccionConfig,ManejoConfiguracion"/>
   </configSections>

  <Seccion>
    <BD>
    <add key="name" value="dbKey" />
    <add key="user" value="userBD" />
    <add key="pass" value="123BD" />
    </BD>

    <ReportingService>
    <add key="name" value="Reporting" />
    <add key="user" value="userReport" />
    </ReportingService>

   </Seccion>
</configuration>

回答1:

You can probably deserialize it to the custom section type:

var section = ConfigurationManager.GetSection("Seccion") as ManejoConfiguracion.SeccionConfig;


回答2:

Bah! Forget those crazy configuration objects. Use Linq to XML on it:

var seccion = 
    XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
        .Root.Element("Seccion");

// Now Linq to XML until your heart's content!
var user = (string)seccion.Element("BD").Elements("add")
    .Where(x => (string)x.Attribute("key") == "user")
        .Single().Attribute("value");