Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

<serv:header>
   <serv:response>
      <serv:result>SUCCESS</serv:result>
      <serv:gsbStatus>PRIMARY</serv:gsbStatus>
   </serv:response>
</serv:header>

When I use a statement like this, I get the exception 'Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.'

XDocument doc = XDocument.Parse(xml);
string value = doc.Descendants("serv:header").First().Descendants("serv:response").First().Descendants("serv:result").First().Value;
like image 935
Jim Avatar asked Oct 28 '09 21:10

Jim


2 Answers

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().

like image 137
Pavel Minaev Avatar answered Oct 22 '22 03:10

Pavel Minaev


That colon means that the XML is using namespaces. Based on this blogpost someone posted about LINQ, XML, and namespaces, here's a version of your code that you might want to try.:

static XName serv(string name)
{
  return XNamespace.Get("<THE_NAMESPACE_URL>") + name;
}

XDocument doc = XDocument.Parse(xml);
string value = doc.Descendants(serv("header")).First().Descendants(serv("response")).First().Descendants(serv("result")).First().Value;
like image 6
Edward Dale Avatar answered Oct 22 '22 03:10

Edward Dale