C# c linq Xdocument

C# c linq Xdocument,c#,xml,linq,C#,Xml,Linq,我这样称呼wcf服务: XDocument xdoc = null; xdoc = XDocument.Load("http:\\www.mydomain.com\service\helloservice"); 我从WCF收到一个xml片段,如下所示: <ArrayOfstring><string>hello</string><string>world</string><string>!</string><

我这样称呼wcf服务:

XDocument xdoc = null;
xdoc = XDocument.Load("http:\\www.mydomain.com\service\helloservice");
我从WCF收到一个xml片段,如下所示:

<ArrayOfstring><string>hello</string><string>world</string><string>!</string></ArrayOfstring>
当我执行xdoc.degenantnodes时,我得到:

[0] "<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <string>HELLO</string>
</ArrayOfstring>"

[1] "<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">HELLO</string>"

[2] "Hello"

我对这个很陌生,我不明白为什么linq不会返回结果…我应该使用哪个Xdocument特性?如果有人能指点一下,我们将不胜感激。谢谢

我确实编译了代码,看起来一切都很好。您刚刚错过的一点是Xml文档中的斜杠字符。最后一个字符串标记未关闭,并导致异常

<ArrayOfstring><string>hello</string><string>world</string><string>!</string></ArrayOfstring>
干杯

更新


尝试此操作,您需要将其强制转换为期望的类型才能获得值

       var i = from n in xdoc.Descendants("ArrayOfstring")
                select new { text = (string)n.Element("string")};

当你调用没有参数的后代时,你会得到什么?当我调用xdoc.Root.Elementsstring时,我什么也得不到?非常有趣。我已经更新了答案,以包含示例控制台程序的代码。请确保在最后一个字符串元素中包含了缺少的结束斜杠。请记住,如果在返回的XML中有名称空间,则方法将不同。这个答案基于您在问题中包含的XML。谢谢。请看看我从WCF服务中得到了什么。我已经更新了我原来的帖子。它显示了当我执行xdoc.degenantnodesi更新代码以包含名称空间支持时得到的结果。现在试试这个。xml中的名称空间用于避免名称冲突。假设您有两个元素名称相同的xml文档,当您合并这两个文档时,如何知道它们来自哪个文档,命名空间有助于解决这些类型的问题。googleforxm名称空间,您将为此获得大量资源。
using System;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Porgram
    {
        static void Main(string[] args)
        {
            string xml = "<ArrayOfstring  xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><string>hello</string><string>world</string><string>!</string></ArrayOfstring>";
            XDocument doc = XDocument.Parse(xml);

            XNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";

            var text = from str in doc.Root.Elements(ns + "string")
                    select str.Value;
            foreach (string str in text)
            {
                Console.WriteLine(str);
            }
            Console.ReadKey();
        }
    }
}
       var i = from n in xdoc.Descendants("ArrayOfstring")
                select new { text = (string)n.Element("string")};