Vagharsh Kandilian Vagharsh Kandilian - 3 months ago 14
PowerShell Question

casting to XML by default parsing HTML tags too

I have an XML document which contains this

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<description>Only applicable if &quot;server&quot; is set to default.</description>
</context-param>
</web-app>


$gcXML = Get-Content -Path "C:\temp.xml"
Write-Output $gcXML


The
&quot;
are preserved in the code above, but not in the code below:

$xdoc = [xml] $gcXML
$xdoc.'web-app'.'context-param'.'description'


Here
&quot;
is being parsed as
"
, which I don't want. Output is:


Only applicable if "server" is set to default.


How can I preserve the
&quot;
?

Answer

You might re-encode the string if that's what you need and you do not wish to (or cannot) change the XML content:

# Load the System.Web assembly
Add-Type -Assembly System.Web
[System.Web.HttpUtility]::HtmlEncode($xdoc.'web-app'.'context-param'.'description')

Versions of PowerShell older than 5 may need additional parentheses surrounding a complex value:

[System.Web.HttpUtility]::HtmlEncode(($xdoc.'web-app'.'context-param'.'description'))
Comments