xml - 如何在 PowerShell 中编写 Xml.linq?

标签 xml powershell linq-to-xml

我正尝试在 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)

但是我收到一个错误提示

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

最佳答案

我在 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")

关于xml - 如何在 PowerShell 中编写 Xml.linq?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10684299/

相关文章:

java - 有很多单元格作为变量的大表

.net - 使用 xsi :nil in XML

c# - LINQ to XML 查询中的 NullReferenceException

java - 如何在撰写邮件功能中将表面 View 与媒体记录器连接

sql-server - 在 SQL Server 2012 中从 XML 中提取元素名称

powershell - 使用 Powershell 删除过期证书

powershell - 让标准输入进入 Powershell 流

powershell - 如何保存已删除文件的日志?

c# - 如何将 TreeView 序列化为 xml 并将 xml 反序列化回 TreeView?

c# - 使用 System.Xml.Linq 命名空间的显式元素结束标记