Thursday, May 10, 2007

Powershell XML Handling for Empty nodes

Windows Powershell handles xml objects a little inconsistently. If a node is empty, then Powershell treats it as a string. If the node is non-empty, then it treats the node as an XmlNode. You can circumvent this behavior by using the Item() interface.

PS>$x=[xml]"<root/>"
PS>$x.root.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object

PS>$x.Item("root").GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False XmlElement System.Xml.XmlLinkedNode

2 comments:

Anonymous said...

This was helpful, but can only access the first item with that name. Is there an easy way to access the rest of the empty nodes with that name as XmlElements?

Anonymous said...

Thanks dude