我目前正在嘗試獲取一個 Powershell 腳本來從 XML 檔案中提取資訊,并且我一直在嘗試一些不同的東西,比如 Select-Xml 和 SelectNodes,但我很掙扎。資訊格式如下:
<school>
<students>
<student name="Bob" subject="Math" year="5">
<details SID="38571273" code="1122" group="" />
</student>
<student name="John" subject="Science" year="5">
<details SID="38343555" code="1123" group="" />
</student>
</students>
</school>
我想提取姓名、學科、年份、SID、代碼和組等資訊,并將其存盤在每個學生的陣列中,以便進行處理。我正在撰寫一個 Powershell 腳本來執行此操作,但我對它以及 XML 都很陌生。任何幫助將不勝感激!
uj5u.com熱心網友回復:
對于像這樣的簡單任務,您可以使用點符號訪問 XML 項,即$xml.school.students.student給出一個<student>元素陣列。
之后,您可以使用select(aka Select-Object) 來挑選某些屬性。按名稱直接屬性或名稱/運算式對(@{name='...', expression={...}}對于更復雜的屬性,或者如果您想重命名結果“列”:
$xml.school.students.student | select name,subject,year,@{n='SID'; e={$_.details.SID}}
給出一個PSCustomObjects 陣列:
名稱 學科 年份 SID ---- -------- ---- --- 鮑勃數學 5 38571273 約翰科學 5 38343555
uj5u.com熱心網友回復:
使用更新的 XML,我修改了我的答案 -
我想這就是你要找的。您只需要更新 xml 的路徑。
$XMLPath = "ENTER_PATH"
function Get-StudentInfo {
param (
$xPATH,
$title)
Select-Xml -Path $XMLPath -XPath "/school/students/$xPATH" | ForEach-Object { $_.Node.$title }
}
$students = [PSCustomObject]@{
Names = Get-StudentInfo -xPath "student" -title "name"
Subjects = Get-StudentInfo -xPath "student" -title "subject"
Years = Get-StudentInfo -xPath "student" -title "year"
SIDs = Get-StudentInfo -xPath "student/details" -title "SID"
Codes = Get-StudentInfo -xPath "student/details" -title "code"
Groups = Get-StudentInfo -xPath "student/details" -title "group"
}
$students.Names
從那里您將擁有一個具有屬性的物件$students,每個屬性都有一個陣列。
Names : {Bob, John}
Subjects : {Math, Science}
Years : {5, 5}
SIDs : {38343555, 38343555}
Codes : {1123, 1123}
Groups : {, }
獲取您將使用的所有學生姓名$students.names或主題的串列$students.subjects
僅加載一次 XML 檔案的版本,而不是每次呼叫一次Get-StudentInfo:
$students = Select-Xml -Path "test.xml" -XPath '/school/students/student' | Select-Object @(
@{name='Name'; expr={ $_ | Select-Xml '@name' }}
@{name='Subject'; expr={ $_ | Select-Xml '@subject' }}
@{name='Year'; expr={ $_ | Select-Xml '@year' }}
@{name='SID'; expr={ $_ | Select-Xml 'details/@SID' }}
@{name='Code'; expr={ $_ | Select-Xml 'details/@code' }}
@{name='Group'; expr={ $_ | Select-Xml 'details/@group' }}
)
$students
結果
名稱 學科 年份 SID 代碼組 ---- -------- ---- --- ---- ----- 鮑勃數學 5 38571273 1122 約翰科學 5 38343555 1123
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444715.html
