简体   繁体   English

如何在Powershell中将列表转换为xml?

[英]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. 我有不同的xml文件,我必须将所有不同的“item”节点组合到一个新的xml文件中。

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. 我已经能够获取节点并将它们提取到列表中,但现在我很难将该列表转换为xml文件。

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. 我试图将列表转换为xml文件usint convertTo-XML,但由于某种原因,xml文件中没有任何项目。 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 我得到一个空的xml文件

It is all about how out-file deals with XML variables. 这完全是关于out-file如何处理XML变量。 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 首先,我们将使用像这样的out-file输出这个变量

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

without convert it to XML. 没有将其转换为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. 当然,当它作为XML文件打开时,它将是空的,但是当使用记事本编辑它时,它将显示我们输入的字符串。 after that we will convert to XML then out it as you did in your code. 之后我们将转换为XML,然后像在代码中那样将其转换为XML。

$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文件将为空,但在编辑文件test2.xml时,它将包含如下内容:

xml Objects xml对象

--- ------- --- -------

version="1.0" encoding="utf-8" Objects version =“1.0”encoding =“utf-8”对象

and this the same result you will see if you typed $xXML in the shell. 如果你在shell中输入$xXML ,你会看到相同的结果。 So out-file just out the results which passes through the pipeline. 因此out-file只是输出通过管道的结果。 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.innerxml的XML表示,我更喜欢使用这些方法之一将任何XML数据保存到文件。

$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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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