views:

71

answers:

2

I have the following XDocument:

<SomeDoc Id="73" Protocol="rahrah" xmlns="http://schemas.company.com/rah/rah2/2005/"&gt;
  <Prop1>11111</Prop1> 
  <Prop2>77777</Prop2> 
  <Prop3>88888</Prop3> 
</SomeDoc>

And I want to extract the value in Prop1.

I use the following code:

var prop1 = xml.Element("Prop1");

But prop1 is being set to null. Am I trying to extract the element correctly?

+2  A: 

I'm assuming that xml is the XDocument object itself.

An XDocument object contains the root element, not its children. You need to write xml.Root.Element("Prop1");.

EDIT: You also need to include the namespace, like this:

XNamespace ns = "http://schemas.company.com/rah/rah2/2005/";
xml.Root.Element(ns + "Prop1");
SLaks
Does the namespace need to be prefixed to the property name? I'm still only getting null returned.
Josh Smeaton
That did the trick. Thanksvar ns = xml.Root.Name.Namespace;
Josh Smeaton
A: 

Could you post the code that you are using to populate the xml variable?

My wild guess is that XDocument is not recognizing the xml fragment as a valid document. I think that XDocument is expecting the <?xml version="1.0"?> root node. You might need to use XmlTextReader instead of XDocument.

hectorsosajr
Wrong. Otherwise, he would get an exception.
SLaks