【问题标题】:Reading custom machine.config elements using XmlDocument?使用 XmlDocument 读取自定义 machine.config 元素?
【发布时间】:2013-01-24 09:40:38
【问题描述】:

在 machine.config 文件中有一些由 3rd 方软件编写的元素,因此看起来像这样:

<configuration>
    <configSections>
    ...
    </configSections>

    ...

    <Custom>
        <Level1> ... 
        </Level1>

        <Level2> ... 
        </Level2>

        <Level3>
            <add key="key_text1" value="s1" />
            <add key="key_text2" value="s2" />
            <add key="key_text3" value="s3" />
        </Level3>
    </Custom>
</configuration>

我想得到例如“value”属性的值(“s2”),其中 key="key_text2" 来自 configuration/Custom/Level3 节点。到目前为止,我尝试将 machine.config 作为 XML 打开并从那里开始工作:

Configuration config = ConfigurationManager.OpenMachineConfiguration();
XmlDocument doc = new XmlDocument();
doc.LoadXml(config.FilePath);

但是,我收到 XmlException“根级别的数据无效。”。我也不知道如何直接使用配置类方法来完成这项工作。任何想法将不胜感激。

【问题讨论】:

    标签: c# .net xml xmldocument machine.config


    【解决方案1】:

    使用RuntimeEnvironment.SystemConfigurationFile 获取machine.config 位置:

    XmlDocument doc = new XmlDocument();
    doc.Load(RuntimeEnvironment.SystemConfigurationFile);
    

    还有,为什么不使用 Linq to Xml?

    XDocument xdoc = XDocument.Load(RuntimeEnvironment.SystemConfigurationFile);
    var element = xdoc.XPathSelectElement("//Custom/Level3/add[@value='s2']");
    if (element != null)
        key = (string)element.Attribute("key");
    

    【讨论】:

    • 谢谢,非常有用。两个答案(动物和你的)实际上都有效。然而,我不得不使用下面的代码来代替上面的代码来让它工作:var query = "/configuration/Custom/Level3/add[@value='s2']"; var dbElement1 = xdoc.XPathSelectElement(query); string key = dbElement1.Attribute("value").Value;
    【解决方案2】:

    尝试使用Load() 方法而不是LoadXml()

    doc.Load(config.FilePath);
    

    我还建议您查看 XDocument 而不是 XmlDocument。从配置文件中获取该值时,LINQ 将非常有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多