この記事は2008/03/03にわんくまブログで書いたものです。
今週は、PowerShellでのXMLの取り扱いについてまとめていこうかと思います。
まずはXMLファイルの読み込みから。
VB.NETだとXmlDocumentは
Dim xmlDoc As New System.Xml.XmlDocument xmlDoc.Load("C:\Work\Test.xml")
みたいに記述します。
PowerShellでは
[xml]$doc = Get-Content "C:\Work\Test.xml"
と書くと、変数$docにXMLファイルが読み込まれます。
これで読み込むことができるのですが、エンコーディングはきちんと指定することをお勧めします。
エンコーディングを指定する場合は、-encodingパラメータを使用します。
-encodingパラメータには、
を指定することができます。
UTF8で読み込む場合は
[xml]$doc = Get-Content "C:\Work\Test.xml" -encoding UTF8
のように記述します。
で、[xml]でキャストした$docのデータ型はどうなっているかというと(GetType()メソッドで確認)
PS C:\Work> $doc.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False XmlDocument System.Xml.XmlNode
XmlDocumentとなっていることが確認できます。
で、使用可能なメンバーは(Get-Memberコマンドレットで確認)
PS C:\Work> $doc | Get-Member TypeName: System.Xml.XmlDocument Name MemberType Definition ---- ---------- ---------- ToString CodeMethod static System.String XmlNode(PSObject instance) add_NodeChanged Method System.Void add_NodeChanged(XmlNodeChangedEventHandler value) add_NodeChanging Method System.Void add_NodeChanging(XmlNodeChangedEventHandler value) add_NodeInserted Method System.Void add_NodeInserted(XmlNodeChangedEventHandler value) add_NodeInserting Method System.Void add_NodeInserting(XmlNodeChangedEventHandler value) add_NodeRemoved Method System.Void add_NodeRemoved(XmlNodeChangedEventHandler value) add_NodeRemoving Method System.Void add_NodeRemoving(XmlNodeChangedEventHandler value) AppendChild Method System.Xml.XmlNode AppendChild(XmlNode newChild) Clone Method System.Xml.XmlNode Clone() CloneNode Method System.Xml.XmlNode CloneNode(Boolean deep) : たくさんあるので省略 :
このようにPowerShellでは簡単にXMLを取り扱うことが可能です。
Theme design by Jelle Druyts
Pick a theme: BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2 BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009, HIRO
E-mail