Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用XmlDocument读取自定义machine.config元素?_C#_.net_Xml_Xmldocument_Machine.config - Fatal编程技术网

C# 使用XmlDocument读取自定义machine.config元素?

C# 使用XmlDocument读取自定义machine.config元素?,c#,.net,xml,xmldocument,machine.config,C#,.net,Xml,Xmldocument,Machine.config,在machine.config文件中,有由第三方软件写入的元素,因此看起来如下所示: <configuration> <configSections> ... </configSections> ... <Custom> <Level1> ... </Level1> <Level2> ... <

在machine.config文件中,有由第三方软件写入的元素,因此看起来如下所示:

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

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

我还建议您查看XDocument而不是XmlDocumentLINQ在从配置文件获取该值时非常有用。

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

我还建议您查看XDocument而不是XmlDocumentLINQ在从配置文件获取该值时非常有用。

用于获取machine.config位置:

XmlDocument doc = new XmlDocument();
doc.Load(RuntimeEnvironment.SystemConfigurationFile);
还有,为什么不使用Linq转换Xml呢

XDocument xdoc = XDocument.Load(RuntimeEnvironment.SystemConfigurationFile);
var element = xdoc.XPathSelectElement("//Custom/Level3/add[@value='s2']");
if (element != null)
    key = (string)element.Attribute("key");
用于获取machine.config位置:

XmlDocument doc = new XmlDocument();
doc.Load(RuntimeEnvironment.SystemConfigurationFile);
还有,为什么不使用Linq转换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(查询);string key=dbElement1.Attribute(“value”).value谢谢,非常有用。这两个答案(动物的和你的)实际上都有效。但是,我必须使用以下代码来实现它,而不是上面的代码:
var query=“/configuration/Custom/Level3/add[@value='s2']”;var dbElement1=xdoc.XPathSelectElement(查询);string key=dbElement1.Attribute(“value”).value