我该如何在PowerShell中编写Xml.linq?

15

我正在尝试使用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);
}

我尝试了类似于这样的代码:

$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)

但是我遇到了一个错误,提示如下:

调用DescendantNodes时出现异常,需要1个参数:值不能为空

2个回答

30

我用 PowerShell 中的 LINQ 实现了这个功能(取消注释 XML 文档中的某些内容):

[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")

5
如果您要编写PowerShell 模块, 您需要创建一个清单文件,该文件在调用Import-Module MyModule时会加载类似的依赖项。
# Comma-separated assemblies that must be loaded prior to importing this module
RequiredAssemblies = @("System.Xml.Linq")

这是为那些编写模块的人推荐的方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接