1

在 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>

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

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

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

4

2 回答 2

2

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

doc.Load(config.FilePath);

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

于 2013-01-24T09:44:11.377 回答
2

使用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");
于 2013-01-24T09:45:38.100 回答