2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

Hmm, any idea on how that would work for nested information? For example say there is info in doc/title/foo1/bar1/info and info in doc/title/foo1/bar2/info and doc/title/foo2/bar1/info etc...
Try an xpath expression like '//info'. That will find all the 'info' nodes wherever they happen to be.
So, to clarify, I would be able to do doc/title//foo//bar//info?
Not quite. It should be like this: ... | Select-Xml '//info' | ...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.