How to add a xml in web.config?

前端 未结 3 1255
暖寄归人
暖寄归人 2021-01-13 06:52

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 w

相关标签:
3条回答
  • 2021-01-13 07:05

    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 &lt;, > to &gt, & to &amp;, " to &quote;)

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

    • Don't use web.config for this, but a Settings file as @Yuck commented

    That last option is the best one, in terms of ease of development and usage.

    0 讨论(0)
  • 2021-01-13 07:16

    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 ...
    
    0 讨论(0)
  • 2021-01-13 07:21

    The configuration sections in web.config support long strings, but the string has to be a single line of text so they can fit into an attribute:

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

    The string also can't contain quotes or line breaks or other XML markup characters. The data is basically XML and it has to be appropriately encoded.

    For example, if you have XML like this:

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

    it would have to be stored in a configuration value like this:

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

    Which kind of defeats the purpose of a configuration element.

    You might be better off storing the configuration value in a separate file on the file system and read it from there into a string or XmlDocument etc.

    0 讨论(0)
提交回复
热议问题