Reputation: 938
I am having an xml file shown below. By using powershell i need to copy the connectionStrings tag to another xml file.
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>
After copy the destination xml should look like this. And the destination xml is a new file and it is not existing.
Output.xml
<configuration>
<connectionStrings>
<add connectionString="uid=u1;pwd=p1;database=d1" name="connect1" />
</connectionStrings>
</configuration>
How do i achieve this in powershell using xml dom manipulation. Any sample code of XML manipulation of this.
Upvotes: 1
Views: 197
Reputation: 938
I got some clue from your answer. Thank you so much for the help. Updating solution which i got. It might be helpful for others.
$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")
Upvotes: 0
Reputation: 4020
Not the most elegant solution, and can be used to delete other nodes on other docs.
$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")
Upvotes: 2