晴耕雨読

working in the fields on fine days and reading books on rainy days

PowerShellでXMLデータを読み取る

型名を使った型変換(キャスト)によって、内部的にコンストラクタが呼び出されます。 PowerShell には XML 型が組み込まれており、キャストによって XML の文字列から連想配列(ハッシュテーブル)を作ることができます。

$myXml = [xml] @'
<Store>
  <Product>
    <Name>Apple</Name>
    <Price quantity="3">200</Price>
  </Product>
  <Product>
    <Name>Banana</Name>
    <Price quantity="4">100</Price>
  </Product>
</Store>
'@

PS> $myXml.Store.Product[0].Name
Apple
PS> $myXml.Store.Product[0].Price."#text"
200
PS> $myXml.Store.Product[0].Price.quantity
3

XMLファイルの内容を取得したい場合は Get-Content と組み合わせて使用します。

PS> $xml = [xml](Get-Content sample.xml)

以上です。