使用 powershell 操作 xml 文件 dom 并创建另一个 xml 文件



我有一个如下所示的xml文件。通过使用Powershell,我需要将connectionStrings标签复制到另一个xml文件。

配置.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.web>
      <compilation debug="true" targetFramework="4.7.2" />
      <httpRuntime targetFramework="4.7.2" />
   </system.web>
   <system.codedom>
      <compilers>
         <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
         <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" />
      </compilers>
   </system.codedom>
   <connectionStrings>
      <add connectionString="uid=u1;pwd=p1;database=d1" name="connect1" />
   </connectionStrings>
 <Appsettings>
      <add key="key1" value1="value1" />
  </Appsettings>
</configuration>

复制后,目标 xml 应如下所示。目标 xml 是一个新文件,它不存在。

输出.xml

<configuration>
 <connectionStrings>
      <add connectionString="uid=u1;pwd=p1;database=d1" name="connect1" />
   </connectionStrings>
</configuration>

如何使用 xml dom 操作在 powershell 中实现这一点。对此进行任何 XML 操作的示例代码。

不是最优雅的解决方案,可用于删除其他文档中的其他节点。

$Nodes = @("system.web","Appsettings","system.codedom")
$XMLFile = "C:Config.xml"
$XMLDoc = (Select-Xml -Path $XMLFile -XPath /).Node
$ParentNode = $XMLDoc.configuration
$xml2 = New-Object System.Xml.XmlDocument
$newNode = $xml2.ImportNode($ParentNode, $true)
$xml2.AppendChild($newNode)
Foreach($Node in $Nodes) {
    $Delete = $xml2.SelectSingleNode("//$Node")
    $Delete.ParentNode.RemoveChild($Delete)
}
$xml2.Save("C:Output.xml")

我从你的回答中得到了一些线索。非常感谢您的帮助。我得到的更新解决方案。这可能对其他人有帮助。

$connectionString = "connectionString.config"
[xml]$SourceConfigXml = Get-Content -Path "$connectionString" -Raw
$SourceXmlNode = $SourceConfigXml | Select-Xml -XPath "/connectionStrings"
Write-Output "$SourceXmlNode"
$xml2 = New-Object System.Xml.XmlDocument
[System.XML.XMLElement]$configurationRoot=$xml2.CreateElement("configuration")
$xml2.appendChild($configurationRoot)
[void] $configurationRoot.AppendChild($xml2.ImportNode($SourceXmlNode.Node, $true))
$xml2.Save("C:tempsamplesample1.xml")

最新更新