Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.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# C XML到Linq元素名称不起作用_C#_Xml_Linq - Fatal编程技术网

C# C XML到Linq元素名称不起作用

C# C XML到Linq元素名称不起作用,c#,xml,linq,C#,Xml,Linq,我试图使用C来使用REST web服务。当我试图获取XML字符串中各个数据点的值时,我遇到了一个错误 我得到的XML如下所示: <queryResult xmlns="http://www.example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <records xsi:type="sObject"> <type>Account</type>

我试图使用C来使用REST web服务。当我试图获取XML字符串中各个数据点的值时,我遇到了一个错误

我得到的XML如下所示:

<queryResult xmlns="http://www.example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <records xsi:type="sObject">
        <type>Account</type>
        <Id>0013000000LKOUMAA5</Id>
        <Name>Example Inc.</Name>
        <BillingCountry>US</BillingCountry>
        <Website>http://www.example.com</Website>
        <CreatedById>00530000000i1jAAAQ</CreatedById>
        <CreatedDate>2008-02-04T14:51:23.000Z</CreatedDate>
        <LastModifiedDate>2014-04-02T18:10:32.000Z</LastModifiedDate>
        <LastModifiedById>00580000005pTwAAAU</LastModifiedById>
    </records>
</queryResult>
使用以下代码,我能够解析XML字符串,但它不会返回Name元素的值,而是返回以下错误:对象引用未设置为对象的实例

WebResponse response = request.GetResponse();
XmlReader reader = XmlReader.Create(response.GetResponseStream());
XDoc = XDocument.Load(reader);
XNamespace ns = "http://www.example.com";
IEnumerable<XElement> records = from el in XDoc.Descendants(ns + "records")
                                select el;
foreach (XElement record in records)
{
    Console.WriteLine("Website: " + record.Element(ns + "Website").Value); //This line works
    Console.WriteLine("Name: " + record.Element(ns + "Name").Value); //Returns an error
}

我认为这与元素名是name有关。我花了一整天的时间在这件事上,我在这一点上遇到了麻烦。

我刚刚试过这个。我创建了一个XML文件,其中包含已更改的关闭标记queryResults,以匹配第一个-删除“s”。而且效果很好。流是否返回正确的XML?您是否尝试过将StreamReader与.ReadToEnd一起使用,然后使用XDocument=XDocument.Parsestream?@malik您的权利。我只是假设它不起作用,然后切换到XName,它起作用了,但删除它仍然起作用。也许我应该删除我的答案,因为XName在这种情况下并不重要。即使我认为人们应该使用XName而不是串联。@CharlesNRice如果你想保留你的答案,我也会将代码放在using块中。e、 g.使用XmlReader=XmlReader.Createresponse。GetResponseStream@malik我删除了它,因为它不是OP问题的根源。我只是在使用他的代码示例并测试XName。我通常会将它放在using语句中。我尝试过使用StreamReader和.ReadToEnd,但XML字符串相当大,我收到了内存不足异常。