Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Get a specific element

Tags:

c#

.net

xml

xpath

I have an XML doc that looks like this:

<root type="object">
  <totalResults type="number">x</totalResults>
  <itemsPerPage type="number">x</itemsPerPage>
  <startIndex type="number">x</startIndex>
  <schemas type="array">
    <item type="string">x</item>
  </schemas>
  <Resources type="array">
    <item type="object">
      <schemas type="array">
        <item type="string">x</item>
      </schemas>
      <id type="string">x</id>
      <externalId type="null"></externalId>
      <meta type="object">
        <created type="string">x</created>
        <location type="string">x</location>
      </meta>
      <userName type="string">x</userName>
      <emails type="array">
        <item type="object">
          <value type="string">[email protected]</value>
          <primary type="boolean">x</primary>
        </item>
      </emails>
    </item>
  </Resources>
</root>

And I am trying to get the email address like this:

 var emails = xmlContent.Root.Elements("Resources").Elements("item").Elements("Emails");
            foreach (XElement elem in emails)
            {
                Console.Write(elem.Value);
            }

This does not work. Any thoughts on how I can get the email addresses from this type of XML XDocument in C#? I've looked around at a few forums and tutorials but I cannot seem to get a handle on XPaths, etc.

like image 522
VinnyGuitara Avatar asked Apr 18 '26 05:04

VinnyGuitara


1 Answers

 XDocument xdoc = XDocument.Load(new StringReader("<root ...")); //// load xml file
 var emails = xdoc.Descendants("Resources").Descendants("emails").ToList(); //// select all emails

I'm using Descendants because it finds children at any level and it searches entire subtree but Elements only finds immediate children

like image 189
esiprogrammer Avatar answered Apr 19 '26 19:04

esiprogrammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!