简体   繁体   中英

Need a little help with Linq 2 xml

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".

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

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

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>");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM