views:

201

answers:

2

Hi!

I have a similar scenario as this one:

public class TestLinq2Xml
{
  private XElement GenerateSomeXml()
  {
     return XElement.Parse(@"<MyObject>
                                <Properties>
                                   <Name>My object 1</Name>
                                   <Position>0; 0; 0</Position>
                                </Properties>
                             </MyObject>");
  }

public void ExploreXmlNode()
{
  var xmlTree = this.GenerateSomeXml();

  var name = xmlTree.Element("MyObject").Element("Properties").Element("Name").Value;

  Console.WriteLine(name);
}

}

Ok, this is very simplified. ....but it still wont work. Any ideas on what I'm doing wrong here?

Edit:

Oh, almost forgot. The problem is that xmlTree.Element("MyObject") returns an empty linq sequence. Even though I clearly have a node named "MyObject".

+2  A: 

The XElement.Parse returns an XElement which is the <MyObject> node. Try:-

var name = xmlTree.Element("Properties").Element("Name").Value;

AnthonyWJones
Doh! Of course! HAHA. Thanks for the quick reply! =)
Presidenten
+1  A: 

Besides what the previous poster suggested, you can also return an XDocument from your GenerateSomeXml() function so that your linq works.

        private static XDocument GenerateSomeXml()
    {
        return XDocument.Parse(@"<MyObject>
                            <Properties>
                               <Name>My object 1</Name>
                               <Position>0; 0; 0</Position>
                            </Properties>
                         </MyObject>");
    }
Rene