I know that I just wrote a post last week about XPath and namespaces in PowerShell, but at the time I left out one possible way of dealing with namespaces, because it’s not the right way of doing things. However, sometimes it’s nice to have options, and when you’re working on the command-line in PowerShell, or just trying to figure out a proof-of-concept call to a web service, you really don’t need to deal with namespaces correctly, you just need it to work.
With that in mind, I present to you the fourth option: just strip the namespaces out! The simplest way to do that is to run the XML through an XSL stylesheet which just outputs the local-name() of each node (including attributes), and remove any namespace definitions (processing instructions).
<xsl:output method="xml" indent="yes">
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates>
</xsl:apply-templates>
</xsl:copy>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()">
</xsl:apply-templates>
</xsl:element>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select=".">
</xsl:value-of>
</xsl:attribute>
</xsl:template></xsl:template></xsl:template></xsl:output></xsl:stylesheet>
That stylesheet and the basic steps of the process will work anywhere, from Java to C# to the web … but since my current language of choice for prototyping is PowerShell, I’ll show you how to implement it there as Remove-XmlNamespace. Once you have that, I think you’ll see that it was relatively simple for me to write a new Select-XML which adds a parameter RemoveNamespace which is implemented by calling this Remove-XmlNamespace …
That actually allows you to call Select-Xml with the -RemoveNamespace parameter just as though the namespaces didn’t exist. Of course, the returned XML nodes will, in fact, NOT have namespaces … so they may not be quite the same as the source, but the data will all be there.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=bba0ce48-3de7-4675-8c1a-a449e3ae8a96)