How can I get attribute from subsection webconfig C#?
Asked Answered
T

2

2

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>
Townshend answered 19/2, 2015 at 6:33 Comment(0)
W
5

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");
Weisbart answered 19/2, 2015 at 6:55 Comment(2)
Thank for your answer, but I'd be worried if memory use was exponential based on the size of the XML document. How can I do to read XDocument from Cache.Townshend
You would only use this once, statically initialized of course. Not sure how big you think a .config should get, or why you think it's any different than other methods of accessing the .config file.Weisbart
I
1

You can probably deserialize it to the custom section type:

var section = ConfigurationManager.GetSection("Seccion") as ManejoConfiguracion.SeccionConfig;
Ionization answered 19/2, 2015 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.