使用Powershell将子元素添加到XML元素

时间:2017-05-23 04:30:39

标签: xml powershell powershell-v3.0

我有一个XML文档,我正在循环并在文件存在时下载并将其保存到磁盘。 我想更新XML文件以包含我保存数据的位置。我怎样才能做到最好?

XML文件示例:

<Invoices xmlns="http://example.com/">
  <invoice>
    <ContractorName>TEST contractor</ContractorName>
    <Invoice_Number>12345</Invoice_Number>
    <Invoice_Date>2017-05-20</Invoice_Date>
    <Invoice_Amount>100.00</Invoice_Amount>
    <Invoice_Hyperlink>https://example.com/path/files/file.pdf</Invoice_Hyperlink>
  </invoice>
  <invoice>
    <ContractorName>TEST contractor 2</ContractorName>
    <Invoice_Number>98765</Invoice_Number>
    <Invoice_Date>2017-05-20</Invoice_Date>
    <Invoice_Amount>1000.00</Invoice_Amount>
  </invoice>
</invoices>

我的脚本如下所示,用于循环遍历XML数据并在本地保存文件。

$Invoicesfile = "D:\Download\invoices.xml"
[xml]$Invoice = Get-Content $Invoicesfile -Raw 

$InvoiceDestinationDir = "D:\Invoices_Downloaded\" 

foreach ($r in $Invoice.Invoices.invoice)
{
    If($r.Invoice_Hyperlink -ne $null){

        $Directory = $InvoiceDestinationDir + $r.ContractorName + "\"+ $InvoiceDate.ToString('yyyy') + "\" + $InvoiceDate.ToString('MM-MMM') + "\" + $InvoiceDate.ToString('dd')

        #Test if destination directory exists and create it if it doesn't
        if (!(Test-Path $Directory))
        {
            New-Item $Directory -type directory | Out-Null
        }
        #set destination to destination directory and files name consisting of Jobcode, 
        $destination = $Directory +"\"+  $r.Invoice_Number +"_" + $r.Invoice_Date +  $r.Invoice_Hyperlink.SubString($r.Invoice_Hyperlink.LastIndexOf('.'))

        Invoke-WebRequest -Uri $r.Invoice_Hyperlink -OutFile $destination
   }
}

我发现的所有示例似乎都在使用CreateElement下面的示例,但是我无法使其工作,因为上面示例中的$rSystem.Xml.XmlLinkedNode和{ {1}}似乎仅适用于CreateElemntSystem.Xml.XmlNode但我希望该元素位于$Inovices

$Invoice.Invoices.invoice

任何建议都会受到赞赏。我要寻找的结果是用以下内容保存上述文件。

[xml] $doc = Get-Content($filePath)
$child = $doc.CreateElement("newElement")
$doc.DocumentElement.AppendChild($child)

1 个答案:

答案 0 :(得分:0)

您找到的代码段工作正常。 $Invoice.Invoices.Invoice是一个包含XmlLinkedNodes

的数组

在foreach循环前使用CreateElement()$Invoice

$Invoicesfile = "D:\Download\invoices.xml"
[xml]$Invoice = Get-Content $Invoicesfile -Raw 

$InvoiceDestinationDir = "D:\Invoices_Downloaded\"

$child = $Invoice.CreateElement("Local_File")

foreach ($r in $Invoice.Invoices.Invoice){...}

在您的foreach中,您可以将$child附加到您实际工作的节点

If($r.Invoice_Hyperlink -ne $null){
        $r.appendchild($child)
        $InvoiceDate = [datetime]::ParseExact($r.Invoice_Date, 'yyyy-MM-dd', $null)

如您所见,我从您的xml中解析了日期,以便能够使用$InvoiceDate.ToString() - 方法

构建$destination - 路径后,您可以使用$r.Local_File = $destination

将该路径分配给新节点