How to query an XDocument with LINQ when elements have a colon in their name?

后端 未结 2 2202
-上瘾入骨i
-上瘾入骨i 2021-02-18 16:16

I am trying to use LINQ to XML in an with the XDocument object. How do you query the result element in the example below?


   

        
2条回答
  •  萌比男神i
    2021-02-18 17:00

    serv in your XML is a namespace prefix. It has to be associated with some URI, that identifies the namespace. Look for an attribute like this in your XML:

    xmlns:serv="..."
    

    The value inside the quotes will be the namespace. Now, in your C# code, you use that URI to create an XNamespace object:

    private static readonly XNamespace serv = "...";
    

    And then you can use that in queries like this:

    string value = doc
        .Descendants(serv + "header").First()
        .Descendants(serv + "response").First()
        .Descendants(serv + "result").First()
        .Value;
    

    By the way, you should consider using .Element() rather than .Descendants().First().

提交回复
热议问题