How to use XElement ?

Using (or providing) Microsoft.NET Classes

How to use XElement ?

Postby PGilbert on Fri Dec 23, 2016 1:31 pm

If you define the variable 'myMusic' with the following:

Code: Select all
<Music>
  <Album Title="Chris Sells Live" Artist="Chris Sells" ReleaseDate="2/5/2008" />
  <Album Title="The Road to Redmond" Artist="Luka Abrus" ReleaseDate="4/3/2008" />
  <Album Title="The Best of Jim Hance" Artist="Jim Hance" ReleaseDate="6/2/2008" />
</Music>


and ⎕USING with the following:
Code: Select all
⎕USING←'System.Xml.Linq,System.Xml.Linq.dll'


then you can get an XElement the following way:
Code: Select all
xel←XElement.Parse(⊂myMusic)


the following line is expected to work but cause a DOMAIN ERROR:
Code: Select all
      xel.Elements(⊂'Album')
DOMAIN ERROR
      xel.Elements(⊂'Album')
     ∧


I have tried many things but nothing is working. Is there a way to make this work ?

Thanks in advance,

Pierre Gilbert
User avatar
PGilbert
 
Posts: 436
Joined: Sun Dec 13, 2009 8:46 pm
Location: Montréal, Québec, Canada

Re: How to use XElement ?

Postby gil on Sun Dec 25, 2016 7:01 am

Hi Pierre

I've never used this before, but testing in v15.0 I got an error message suggesting the syntax for the method call is at fault:
Code: Select all
System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements()
System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName)


Reading about it on msdn I see that the Elements method requires an instance of the XName class as an argument. XName in turn doesn't have a constructor, but offers a Get method that will return an instance from String. This works for me:

myMusic defined as:
Code: Select all
<Music>
  <Album Title="Chris Sells Live" Artist="Chris Sells" ReleaseDate="2/5/2008">
    <Song Title="Track 1" />
    <Song Title="Track 2" />
    <Song Title="Track 3" />
  </Album>
  <Album Title="The Road to Redmond" Artist="Luka Abrus" ReleaseDate="4/3/2008">
    <Song Title="Track A" />
    <Song Title="Track B" />
    <Song Title="Track C" />
    <Song Title="Track D" />
  </Album>
  <Album Title="The Best of Jim Hance" Artist="Jim Hance" ReleaseDate="6/2/2008">
    <Song Title="Track I" />
    <Song Title="Track II" />
  </Album>
</Music>

I then query the document like this:
      (⌷ xel.Descendants ⍬).Name
Album Song Song Song Album Song Song Song Song Album Song Song
(⌷ xel.Elements ⍬).Name
Album Album Album
⍴ ⌷ xel.Elements XName.Get⊂'Song'
0
⍴ ⌷ xel.Descendants XName.Get⊂'Song'
9


Merry Christmas!
gil
 
Posts: 71
Joined: Mon Feb 15, 2010 12:42 am

Re: How to use XElement ?

Postby PGilbert on Sun Dec 25, 2016 2:14 pm

Many Thanks Gil, this has been troubling me for a long time and you found the answer.

Merry Christmas to you to !
User avatar
PGilbert
 
Posts: 436
Joined: Sun Dec 13, 2009 8:46 pm
Location: Montréal, Québec, Canada


Return to Microsoft.NET

Who is online

Users browsing this forum: No registered users and 1 guest