简体   繁体   中英

How to convert list to xml in Powershell?

I have different xml files from which I have to combine all the different "item" -nodes to a new xml file.

I have been able to get the nodes and extract them to a list, but now I'm having difficulties to convert that list to a xml file.

I have tried to convert the list to a xml file usint convertTo-XML, but for some reason the xml file doesn't have any items in it. I have checked the list, and that does have the items.

$OutComId = @()
Get-ChildItem $rootFolder\$country\$projectsToCheck\$mmyyyy | ForEach-Object {
    [xml]$xml = Get-Content -Encoding UTF8 $rootFolder\$country\$projectsToCheck\$mmyyyy\$_
    $nodes = $xml.SelectNodes("//Costs")

    foreach($node in $nodes) {
        $OutComId += $node.Item
    } 
}
$exportPath = "$rootFolder\$country\$projectsToCheck\$mmyyyy"
$OutComId | ConvertTo-XML |  Out-File "$exportPath\combined.xml"

I get an empty xml -file

It is all about how out-file deals with XML variables. to understand this you need to test it on a simple variable, lets say we have a variable

$x="This an XML variable"

. first we will out this variable using out-file like this

$x|out-file -path C:\\test.xml

without convert it to XML. Of course when open it as XML file it will be empty but when editing it using notepad it will show the string we entered. after that we will convert to XML then out it as you did in your code.

$xXML=$x|convertto-XML

$xXML|out-file C:\\test2.xml

As before the XML file will be empty but when editing the file test2.xml it will contain something like this:

xml Objects

--- -------

version="1.0" encoding="utf-8" Objects

and this the same result you will see if you typed $xXML in the shell. So out-file just out the results which passes through the pipeline. if you want to see the XML representation you need to type $xXML.innerxml , i prefer to save any XML data to file using one of these methods.

$xXML.save("C:\\test3.xml")

OR

$x |Export.CliXML -path "C:\\test4.xml"

So instead of the last line in your code you can just type

$OutComId | Export-CliXML "$exportPath\\combined.xml"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM