Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write Xml.linq in PowerShell?

I'm am trying to do this in PowerShell:

XDocument document = XDocument.Load(@"web.config");

var comments = document.Descendants("client").DescendantNodes().OfType<XComment>().ToArray();

foreach (var comment in comments)
{
    XElement unCommented = XElement.Parse(comment.Value);
    comment.ReplaceWith(unCommented);
}

I've tried something like this:

$xDoc = [System.Xml.Linq.XDocument]::Load("web.config")

[System.Collections.Generic.IEnumerable[System.Xml.Linq.XElement]] $enum = $xDoc.Descendants("client")
       
$clients = [System.Xml.Linq.Extensions]::DescendantNodes($enum)

But I am getting an error saying

Exception calling DescendantNodes with 1 argument(s): value cannot be null

like image 779
Marius Avatar asked May 21 '12 11:05

Marius


2 Answers

I got this to work, (uncommenting something from an xml document) using linq in powershell:

[Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq") | Out-Null

$xDoc = [System.Xml.Linq.XDocument]::Load("web.config")
$endpoints = $xDoc.Descendants("client") | foreach { $_.DescendantNodes()}               
$comments = $endpoints | Where-Object { $_.NodeType -eq [System.Xml.XmlNodeType]::Comment -and $_.Value -match "net.tcp://localhost:9876/RaceDayService" }        
$comments | foreach { $_.ReplaceWith([System.Xml.Linq.XElement]::Parse($_.Value)) }

$xDoc.Save("web.config")
like image 77
Marius Avatar answered Sep 17 '22 14:09

Marius


If you were to write PowerShell Modules, you'd create a Manifest file, which would have similar dependencies loaded upon Import-Module MyModule call:

# Comma-separated assemblies that must be loaded prior to importing this module
RequiredAssemblies = @("System.Xml.Linq")

This is the recommended way for those who write modules.

like image 40
Ostati Avatar answered Sep 16 '22 14:09

Ostati