How to use XElement ?

Using (or providing) Microsoft.NET Classes
Post Reply
User avatar
PGilbert
Posts: 440
Joined: Sun Dec 13, 2009 8:46 pm
Location: Montréal, Québec, Canada

How to use XElement ?

Post by PGilbert »

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
gil
Posts: 72
Joined: Mon Feb 15, 2010 12:42 am

Re: How to use XElement ?

Post by gil »

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!
User avatar
PGilbert
Posts: 440
Joined: Sun Dec 13, 2009 8:46 pm
Location: Montréal, Québec, Canada

Re: How to use XElement ?

Post by PGilbert »

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

Merry Christmas to you to !
Post Reply