Search code examples
xelement

Query specific element in XElement


I have this code that I'm trying to tweak to get back just the messages element:

    public static void Main(string[] args)
    {

        Console.WriteLine("Querying tree loaded with XElement.Load");
        Console.WriteLine("----");
        XElement doc = XElement.Parse(@"<magento_api>
              <messages>
                <error>
                  <data_item>
                    <code>400</code>
                    <message>Attribute weight is not applicable for product type Configurable Product</message>
                  </data_item>
                  <data_item>
                    <code>400</code>
                    <message>Resource data pre-validation error.</message>
                  </data_item>
                </error>
              </messages>
            </magento_api>");
        IEnumerable<XElement> childList =
            from el in doc.Elements()
            select el;
        foreach (XElement e in childList)
            Console.WriteLine(e);
    }

I'd like to get the following results:

<message>Attribute weight is not applicable for product type Configurable Product</message>
<message>Resource data pre-validation error.</message>

I'm new to the whole querying XElement thing, so any help is appreciated.


Solution

  • You should use the following:

    foreach (var descendant in doc.Descendants().Where(x => x.Name == "message"))
    {
        Console.WriteLine(descendant);
    }
    

    Also, I would suggest to execute the following:

    foreach (var descendant in doc.Descendants())
    {
        Console.WriteLine(descendant);
    }
    

    To gain a better understanding of how XElement works.