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
  • 33,050
  • 15
  • 95
  • 195

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
  • 25,034
  • 12
  • 68
  • 112