我有一个如下所示的xml文件。通过使用Powershell,我需要将connectionStrings标记复制到另一个xml文件。
Config.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=\"Web\" /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是一个新文件,并且不存在。
Output.xml
<configuration>
<connectionStrings>
<add connectionString="uid=u1;pwd=p1;database=d1" name="connect1" />
</connectionStrings>
</configuration>
如何使用XML dom操作在powershell中实现此目的。 XML操作的任何示例代码。
答案 0 :(得分:2)
这不是最优雅的解决方案,可用于删除其他文档上的其他节点。
$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")
答案 1 :(得分:0)
我从你的回答中得到了一些线索。十分感谢你的帮助。更新我得到的解决方案。这可能对其他人有帮助。
$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:\temp\sample\sample1.xml")