簡體   English   中英

PowerShell - 從 CSV 轉換為 XML 並更新 XML 記錄

[英]PowerShell - Convert from CSV to XML & update XML records

我試圖遍歷一個文件夾,導入所有 CSV 文件,將它們轉換為 XML,根據 CSV 數據更改 XML 值並將它們導出到不同的文件夾,同時保持相同的名稱。

#CSV 文件格式(無標題)

booker12,9012,Rachel,Booker
grey07,2070,Laura,Grey
johnson81,4081,Craig,Johnson
jenkins46,9346,Mary,Jenkins
smith79,5079,Jamie,Smith  

更新

#Desired XML 文件格式(我希望能夠將 CSV 文件中的數據直接提取到 XML 值中)

<?xml version="1.0"?>
<book>
      
      <title>booker12</title>
      <acode>9012</acode>
      <name>Rachel,Booker</name>
   </book>

我已經設法獲取所有 CSV 文件,將它們移動到一個文件夾並使用下面的代碼“重命名為 XML”。

# Folder containing source CSV files
$folderPath = 'C:\Users\somename\Desktop\FOLDER\Import\'

# Destination folder for the new files
$folderPathDest = 'C:\Users\somename\Desktop\FOLDER\Output\'

# Generate a list of all files in the folder and pipe it to ForEach-Object
Get-ChildItem $folderPath -Name |

# Loop through each file
ForEach-Object { 

    # Combines source folder path and file name
    $filePath = $folderPath + $_

    # Combines destination folder and file name
    $filePathdest = $folderPathDest + $_


    # Imports CSV file, exports as CSV to the desired destination
    Import-Csv $filePath |
    Export-Csv -Path $filePathDest –NoTypeInformation
}


#Converts all items from output folder to XML
Get-ChildItem -Path 'C:\Users\somename\Desktop\FOLDER\Output\' |
   ForEach-Object {
       (Get-Content -Path $_.FullName) |
            Set-Content -Path $_.FullName -Encoding UTF8
       Rename-Item -NewName "$($_.BaseName).xml" -Path $_.FullName
    }

我找到了一個類似的代碼片段,我一直在玩它,但我不確定如何將它集成到我當前的代碼中。 使用powershell從csv格式化xml字段

foreach ($router in $routers) {

$router_hostname = $router.hostname
$router_ip = $router.ip

$xml = @"
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<root expanded="True" name="Test MSP" type="database" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<connection name=$router_hostname type="PuTTY">
<name>$router_hostname</name>
<protocol>Telnet</protocol>
<host>$router_ip</host>
<port>23</port>
<session>Default Settings</session>
<connectiontimeout>1500</connectiontimeout>
<logintimeout>1000</logintimeout>
<passwordtimeout>1000</passwordtimeout>
<commandtimeout>1000</commandtimeout>
<postcommands>False</postcommands>
</connection>
</root>
"@

任何幫助,將不勝感激。 非常感謝。

您可以使用Here-Strings在一個循環中創建 xml 文件,如下所示:

# Folder containing source CSV files
$folderPath     = 'C:\Users\somename\Desktop\FOLDER\Import'
# Destination folder for the new files
$folderPathDest = 'C:\Users\somename\Desktop\FOLDER\Output'

# create a template Here-string for the XML (all <book> nodes need to be inside a root node)
$xmlTemplate = @"
<?xml version="1.0" encoding="utf-8"?>
<books>
@@BOOKNODES@@
</books>
"@

# and also a template for the individual <book> nodes
# inside are placeholders '{0}' we will fill in later
$bookTemplate = @"
    <book>
        <title>{0}</title>
        <acode>{1}</acode>
        <name>{2},{3}</name>
    </book>
"@

# Generate a list of all files in the folder and pipe it to ForEach-Object
Get-ChildItem -Path $folderPath -Filter '*.csv' -File | ForEach-Object { 
    # Combines destination path and file name with extension .xml
    $filePathdest = Join-Path -Path $folderPathDest -ChildPath ('{0}.xml' -f $_.BaseName)
    # Import the CSV file
    $data  = Import-Csv -Path $_.FullName -Header Title, Acode, FirstName, LastName
    $books = foreach ($book in $data) {
        # output a <book> section with placeholders filled in
        $bookTemplate -f $book.Title, $book.Acode, $book.FirstName, $book.LastName
    }
    # create the completed XML and write this to file
    $xmlTemplate -replace '@@BOOKNODES@@', ($books -join [environment]::NewLine) |
    Set-Content -Path $filePathdest -Encoding utf8
}

輸出將是這樣的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book>
        <title>booker12</title>
        <acode>9012</acode>
        <name>Rachel,Booker</name>
    </book>
    <book>
        <title>grey07</title>
        <acode>2070</acode>
        <name>Laura,Grey</name>
    </book>
    <book>
        <title>johnson81</title>
        <acode>4081</acode>
        <name>Craig,Johnson</name>
    </book>
    <book>
        <title>jenkins46</title>
        <acode>9346</acode>
        <name>Mary,Jenkins</name>
    </book>
    <book>
        <title>smith79</title>
        <acode>5079</acode>
        <name>Jamie,Smith</name>
    </book>
</books>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM