2

I have this XML:

<?xml version="1.0" encoding="utf-8"?>
<envelope xmlns="myNamespace">
  <response code="123" />
</envelope>

and I want to select the <response> element like this:

XDocument doc = XDocument.Parse(myXmlString);
XElement response = doc.Root.Element("response");

but it returns null. I know the element is there, because doc.Root.FirstNode is the element I need.

What am I missing here?

Bart Friederichs
  • 32,037
  • 14
  • 96
  • 185

1 Answers1

8

you need to include the namespace to get the element:

XDocument doc = XDocument.Parse(myXmlString);
XNamespace ns = "myNamespace";
XElement response = doc.Root.Element(ns + "response");

alternatively, you can use the LocalName to get around using the namespace:

XDocument doc = XDocument.Parse(xml);
XElement response = doc.Descendants().First(x => x.Name.LocalName == "response");
Jonesopolis
  • 24,241
  • 10
  • 66
  • 110