PowerShell: XMLファイルの読み込み

PowerShellでXMLファイルを読み込んで内容を表示する方法を紹介します。 XMLファイルを読み込むための特別なコマンドレットはなく、 Get-Contentコマンドレットでファイルを読み込み、 System.XML.XMLDocument型(xml型)に変換します。

ここでは社員情報を格納していいるxmlファイル 「sample.xml」を読み込みます。
sample.xmlには大枠としてemployees要素(複数形)があり、 その子要素にemployee要素(単数形)があります。 employee要素の子要素としてid、name、yearがあります。

sample.xml
<?xml version="1.0"?>
<employees>
<employee>
	<id>1</id>
	<name>田中</name>
	<year>2000</year>
</employee>
<employee>
	<id>2</id>
	<name>鈴木</name>
	<year>2001</year>
</employee>
<employee>
	<id>3</id>
	<name>佐藤</name>
	<year>2002</year>
</employee>
</employees>

XMLファイルの読み込みは非常にシンプルです。 次のコードのように、 Get-Contentで読み込んで、 [xml]でXML型に変換するだけです。

PowerShell
$content = Get-Content .\sample.xml

$xml = [xml]$content

$xml
実行結果
xml           employees
---           ---------
version="1.0" employees

次はemployee要素の中にあるid、name、year要素のデータを取得(表示)します。

$content = Get-Content .\sample.xml

$xml = [xml]$content

foreach ($employee in $xml.employees.employee){
	Write-Host "-----------"
	$employee.id
	$employee.name
	$employee.year
}

foreach文を使ってemployee要素をループし、 その中にある子要素を取得(表示)しています。

実行結果
-----------
1
田中
2000
-----------
2
鈴木
2001
-----------
3
佐藤
2002

先程はforeach文を使って全てのemployee要素をループしましたが、 要素数を指定してデータを取得することもできます。
次のコードは要素数が0(1番目)のemployee要素のデータを取得しています。 要素数はLengthプロパティで取得します。

$content = Get-Content .\sample.xml

$xml = [xml]$content

$xml.employees.employee[0].id
$xml.employees.employee[0].name
$xml.employees.employee[0].year

Write-Host "要素数"
$xml.employees.employee.Length
実行結果
1
田中
2000
要素数
3
PowerShell
PR