Using Xml.Linq in PowerShell

by Doug Finke on August 7, 2007

in LINQ,PowerShell,Xml

Here are two ways to read an RSS feed with PowerShell. The first uses the Xml.Linq namespace and the second uses the Net.WebClient namespace.Both approaches retrieve the RSS feed differently. The Xml.Linq version returns an XDocument while the WebClient creates an XmlDocument. 

Notice the final output is different between the scripts. The Xml.Linq returns Strings and the WebClient returns and XmlElement object.

The last example shows a C# console reading the same RSS feed.





C# Version


{ 1 trackback }

Tweets that mention Using Xml.Linq in PowerShell --
09.17.10 at 10:02 pm

{ 4 comments… read them below or add one }

Marco Shaw 08.08.07 at 10:59 pm

And for those less familiar with LINQ and .NET… You need .NET 3.5 to have the LINQ class. I don’t think you have any other options but starting a Visual Studio 2008 beta install to get .NET 3.5 libraries.

Marco Shaw 08.08.07 at 11:01 pm
Jamie Thomson 10.20.08 at 3:26 pm

Hi Doug,
This is really really helpful (thank you) and its ALMOST got me to where I need to be. I’m using Xml.Linq in Powershell in order to parse some XML so your code above *almost* gets me there, trouble is that I need to declare an XML namespace for my XDocument.

Here’s my C# code:
XDocument doc = XDocument.Load(xmlReader);

XNamespace ns = @””;
IEnumerable ids = from e in doc.Descendants(ns + “Authority”)
select e.Value;

and my powershell script (so far)
[Reflection.Assembly]::LoadWithpartialName(“System.Xml.Linq”) | Out-Null
$xDoc = [System.Xml.Linq.XDocument]::Load($xmlReader)

Any idea how I declare the namespace?

Thanks very very much in advance.


P.S. Not sure if I can subscribe to the comments here and don’t know if I’ll get an email if you reply so I’ll keep checking back. Thanks.

Jamie Thomson 10.20.08 at 3:41 pm

Not to worry, I’ve figured it out.
[Reflection.Assembly]::LoadWithPartialName(“System.Xml.Linq”) | Out-Null
$xDoc = [System.Xml.Linq.XDocument]::Load($xmlReader)
$ns = [System.Xml.Linq.XNamespace](“”)
$xDoc.Descendants($ns + “Authority”) | ForEach {$_.Element($ns + “Id”).Value}

I’m not actually sure *why* this works (I’ve been using Powershell for about 6 hours so far and don’t yet understand some of the syntax) but nonetheless it works so I’m happy.

Thanks again for the helpful blog.


Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Previous post:

Next post:

You are forbidden!