Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.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# 在获取元素中某个属性的值时,此linq to xml查询中存在一些问题_C#_Xml Parsing_Linq To Xml - Fatal编程技术网

C# 在获取元素中某个属性的值时,此linq to xml查询中存在一些问题

C# 在获取元素中某个属性的值时,此linq to xml查询中存在一些问题,c#,xml-parsing,linq-to-xml,C#,Xml Parsing,Linq To Xml,我有这个app.config文件: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="domain" value="localhost"/> <add key="hostname" value="hostpc"/> </appSettings> </configuration&

我有这个app.config文件:

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <appSettings>

    <add key="domain" value="localhost"/>

    <add key="hostname" value="hostpc"/>

 </appSettings>
 </configuration>
但是我的查询遗漏了一些东西。如果有人能识别出我遗漏了什么,或者怎样才能让它变得更好,那么目前它不起作用

注意:我只想使用linq to xml

尝试使用以下方法:

    XElement doc = XElement.Load("ConsoleApplication1.exe.config");

    var domain = (from appNode in doc.Element("appSettings").Elements("add")
                  where appNode.Attribute("key").Value == "domain"
                  select appNode.Attribute("value").Value).FirstOrDefault();

我使用了app.config文件内容,编写了一个基于控制台的小应用程序,代码如下:

class Program
{
    static void Main(string[] args)
    {
        // Create the query 
        var nodes = from appNode in XElement.Load("App.config").Descendants("appSettings").Elements()
                    where appNode.Attribute("key").Value == "domain"
                    select appNode;

        var element = nodes.FirstOrDefault();
        string value = element.Attribute("value").Value;

        Console.WriteLine(value);

        //Pause the application 
        Console.ReadLine();
    }
}
输出为:localhost


希望这有帮助。如果它在您的机器上不工作,请共享错误详细信息

我正在调试,该域返回的值为域{System.Linq.Enumerable.WhereEnumerableTerator}System.Collections.Generic.IEnumerable{System.Linq.Enumerable.WhereEnumerableTerator}注释没有帮助,请尝试我在回答中共享的代码。如果代码不起作用,请共享您获得的异常详细信息。请更新问题,以包含更多详细信息,如什么是异常、在什么时候获得异常等。这将有助于我们帮助您:)
class Program
{
    static void Main(string[] args)
    {
        // Create the query 
        var nodes = from appNode in XElement.Load("App.config").Descendants("appSettings").Elements()
                    where appNode.Attribute("key").Value == "domain"
                    select appNode;

        var element = nodes.FirstOrDefault();
        string value = element.Attribute("value").Value;

        Console.WriteLine(value);

        //Pause the application 
        Console.ReadLine();
    }
}