How to add a xml in web.config?
Solution 1
If you don't want to write a configuration section handler, you could just put your XML in a custom configuration section that is mapped to IgnoreSectionHandler
:
<configuration>
<configSections>
<section
name="myCustomElement"
type="System.Configuration.IgnoreSectionHandler"
allowLocation="false" />
</configSections>
...
<myCustomElement>
... complex XML ...
</myCustomElement>
...
</configuration>
You can then read it using any XML API, e.g. XmlDocument
, XDocument
, XmlReader
classes. E.g.:
XmlDocument doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlElement node = doc.SelectSingleNode("/configuration/myCustomElement") as XmlElement;
... etc ...
Solution 2
There are several ways of achieving what you want (an XML fragment that is globally and statically accessible to your application code):
The
web.config
is already an XML file. You can write a custom configuration section (as described here) in order to fetch the data from your custom XML.You can encode the XML data (all
<
to<
,>
to>
,&
to&
,"
to"e;
)You can put the XML data in a
<![CDATA[]]>
sectionDon't use
web.config
for this, but aSettings
file as @Yuck commented
That last option is the best one, in terms of ease of development and usage.
Gulshan
Updated on June 05, 2022Comments
-
Gulshan almost 2 years
I have some complex data which is used for application configuration in xml format. I want to keep this xml string in web.config. Is it possible to add a big xml string in web.config and get it in code everywhere?
-
Gulshan about 12 yearsIs it possible to add an array of objects in settings file?
-
Oded about 12 yearsNot an array, as far as I am aware, but you can add collections (there is a built in StringCollection, for example).
-
Gulshan about 12 yearsProbably this is what I looking for.
-
Gulshan about 12 yearsWill u plz tell how can I read the "...complex xml..." as a string in my code?
-
Joe about 12 years@Idorado, I added an example of reading the custom element using the XmlDocument class.
-
Gulshan about 12 yearsThank you Joe This is exactly what i was searching.
-
JohnDoDo over 11 years@Gulshan: It's nice to reward this user if his answer solved your issue by marking the answer as accepted.
-
Boogier almost 10 years<section> describer must be put in <configuration><configSections> And <myCustomElement> in <applicationSettings>
-
Admin over 9 years@Joe, Thanks! Nice and clean way to do it.
-
Admin over 9 years@Boogier, No need to put <myCustomElement> in applicationSettings, because, you can define your own Custom Element in the config file this way.