PowerShell连接多个XML文件

时间:2019-01-19 23:01:42

标签: xml powershell

不确定为什么我会遇到这样的困难,但是我无法弄清楚如何使用包的总体包装将多个XML文件连接在一起,以便我可以轻松地处理数据。

XML文件:

<package>
    <Application>Java</Application>
    <Version>8.0.2010.9</Version>
    <InstallType>Install</InstallType>
    <Installers>
        <Windows10>
            <Architecture>
                <x86>
                    <File1>
                        <FileName>jre-8u201-windows-i586.exe</FileName>
                        <Parameters>/s</Parameters>
                    </File1>
                </x86>
                <x64>
                    <file1>
                        <FileName>jre-8u201-windows-x64.exe</FileName>
                        <Parameters>/s</Parameters>
                    </file1>
                </x64>
                <AMD64>
                    <File1>
                        <FileName></FileName>
                        <Parameters></Parameters>
                        <CustomSuccessCodes></CustomSuccessCodes>
                        <CustomErrorCodes></CustomErrorCodes>
                    </File1>
                </AMD64>
            </Architecture>
        </Windows10>
    </Installers>
</package>

我所拥有的:

$Path = "D:\Desktop\AutoInstall\Packages\Java v8u201\package.xml"
$Xml = New-Object Xml
#$Xml.AppendChild($XML.CreateXmlDeclaration("1.0", "UTF-8", $null)) | Out-Null
$Xml.AppendChild($Xml.CreateElement("Packages")) | Out-Null

$newxml = [xml](Get-Content $Path)
$Xml.ImportNode($newxml.get_DocumentElement(), $true) | Out-Null

$newNode = $newxml.ImportNode($Xml.get_DocumentElement(), $true)
$newxml.DocumentElement.AppendChild($newNode) | Out-Null
$Xml.packages

当我输入$xml.packages时,它应显示以下内容:

Application Version  InstallType Installers
----------- -------  ----------- ----------
Java        8.2.9.23 Install     Installers

1 个答案:

答案 0 :(得分:1)

您的导入方向错误。您正在将创建的新XML文档($xml导入到从XML文件加载的XML文档中。如果运行$newxml.Save([Console]::Out),您将在结账<Packages />之前看到一个节点</package>

<package>
    <Application>Java</Application>
    <Version>8.0.2010.9</Version>
    <InstallType>Install</InstallType>
    <Installers>
        ...
    </Installers>
    <Packages />       <!-- right here -->
</package>

此语句将按照您的需要导入$newxml

$xml.ImportNode($newxml.get_DocumentElement(), $true) | Out-Null

但是您立即丢弃结果(Out-Null),然后以另一种方式进行导入:

$newNode = $newxml.ImportNode($xml.get_DocumentElement(), $true)

这将满足您的要求:

$path = 'D:\Desktop\AutoInstall\Packages\Java v8u201\package.xml'

# create new XML document with <Packages> root node
$xml = New-Object Xml
$xml.AppendChild($xml.CreateElement('Packages')) | Out-Null

# load package XML from file and import it into $xml
$package = New-Object Xml
$package.Load($path)
$imported = $xml.ImportNode($package.DocumentElement, $true)
$xml.DocumentElement.AppendChild($imported) | Out-Null

$xml.Save([Console]::Out)