Reputation: 74
I would like to create a Powershell script that automates parsing an XML, but collecting only certain information from it.
As it stands, right now, my script looks similar to this.
[xml]$xml = Get-Content .\myxml.xml
$foo_sub_length = $xml.report.foos.foo.length - 1
$foo_looper = 0
$foo_looper_brackets = "[$foo_looper]"
if ($foo_sub_length -eq "") {$foo_looper_brackets = ""}
do {
$xml.report.foos.foo$foo_looper_brackets.bar
}
while ($foo_looper -le $foo_sub_length)
Basically, it needs to go through and print out all of the $xml.report.foos.foo.bar values. When I run this script, I receive the error,
Unexpected token 'node_looper_brackets' in expression or statement.
At C:\Users\notarealuser\Desktop\xmlscript.ps1:10 char:55 #not reflective of the above script
+ CategoryInfo : ParserError: (foo_looper_brackets:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
+ $xml.report.foos.foo$foo_looper_brackets <<<< .bar
Any ideas on why or how my looping is not working?
Upvotes: 2
Views: 1105
Reputation: 2888
try this:
[Xml]$doc=@"
<doc><title>
<foo2><bar1><info>1</info></bar1></foo2>
<foo1><bar1><info>2</info></bar1></foo1>
<foo1><bar2><info>3</info></bar2></foo1>
</title></doc>
"@
$doc.CreateNavigator().Select('/doc/title//info') | select value
Upvotes: 1
Reputation: 201652
You might be better off extracting this info with XPath. If you're not using XML namespaces this is pretty trivial (and namespaces only makes it slightly harder):
PS> [xml]'<doc><title>Foo</title><title>Bar</title></doc>' |
Select-Xml '/doc/title' | Foreach {$_.Node.InnerText}
Foo
Bar
Upvotes: 3