How to add xml to web.config?

I have some complex data that is used to configure an application in xml format. I want to save this xml line in web.config. Is it possible to add a large xml string to web.config and get it in all the code?

+4
source share
3 answers

If you do not want to write a configuration section handler, you can simply put your XML in a custom configuration section that maps to IgnoreSectionHandler :

 <configuration> <configSections> <section name="myCustomElement" type="System.Configuration.IgnoreSectionHandler" allowLocation="false" /> </configSections> ... <myCustomElement> ... complex XML ... </myCustomElement> ... </configuration> 

Then you can read it using any XML API, for example. XmlDocument , XDocument , XmlReader . For instance:.

 XmlDocument doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); XmlElement node = doc.SelectSingleNode("/configuration/myCustomElement") as XmlElement; ... etc ... 
+15
source

There are several ways to achieve what you want (an XML snippet that is globally and statically available for your application code):

  • web.config already an XML file. You can write a special configuration section (as described here ) to retrieve data from your custom XML.

  • You can encode XML data (all < to &lt; , > to > , & to &amp; " to &quote; )

  • You can put the XML data in the <![CDATA[]]> section

  • Do not use web.config for this, but the Settings file as @Yuck commented

This last option is the best in terms of ease of development and use.

+5
source

The configuration sections in web.config support long lines, but the line must be a single line of text so that they can fit into the attribute:

  <add name="" value="... some very long text can go in here..." /> 

A string also cannot contain quotation marks or line breaks or other XML markup characters. The data is primarily XML and must be properly encoded.

For example, if you have XML:

  <root> <value>10</value> </root> 

it should be saved in a configuration value such as this:

 <add key="Value" value="&lt;root&gt;&#xD;&#xA; &lt;value&gt;10&lt;/value&gt;&#xD;&#xA;&lt;/root&gt;" /> 

Which type wins the assignment of a configuration item.

Perhaps you better save the configuration value in a separate file in the file system and read it from there to a string or XmlDocument, etc.

0
source

Source: https://habr.com/ru/post/1400981/


All Articles