3

The problem

We want to assign an attribute whose contents already contain entities like " or &.
In this example, we want the title attribute to be Stack "Stacky" Overflow:

$elem = $xml.CreateElement("Site");
$elem.SetAttribute("Title", "Stack "Stacky" Overflow");

But that turns into the following piece of XML output:

<Site Title="Stack &amp;quot;Stacky&amp;quot; Overflow" />


That behaviour is even stated in the documentation about the XmlElement.SetAttribute Method:

In order to assign an attribute value that contains entity references, the user must create an XmlAttribute node plus any XmlText and XmlEntityReference nodes, build the appropriate subtree and use SetAttributeNode to assign it as the value of an attribute.

ComFreek
  • 29,044
  • 18
  • 104
  • 156

3 Answers3

4

The solution

$elem = $xml.CreateElement("Site");

$elemAttr = $xml.CreateAttribute("Title");
$elemAttr.InnerXml = "Stack &quot;Stacky&quot; Overflow";

$elem.SetAttributeNode($elemAttr);

XML output:

<Site Title="Stack &quot;Stacky&quot; Overflow" />
ComFreek
  • 29,044
  • 18
  • 104
  • 156
1

Dont know if this helps

Add-Type -AssemblyName System.Web
$elem = $xml.CreateElement("Site");
$elem.SetAttribute("Title",[System.Web.HttpUtility]::HtmlDecode("Stack &quot;Stacky&quot; Overflow"));
$elem.OuterXml
0
PS> $xml.Site.Title = [System.Security.SecurityElement]::Escape('Stack "Stacky" Overflow')
PS> $xml.Site.Title

Stack &quot;Stacky&quot; Overflow
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • This is also a solution, of course. But in my case, I have got tons of sequences of `&quot` in my string. I think my solution is the more simple one in that situation. There's also the possibility of calling an entity decode function (I don't know the exact name in PS). – ComFreek Nov 04 '12 at 20:18
  • Have you tries setting it the simple way? $xml.Site.Title = 'Stack "Stacky" Overflow' – Shay Levy Nov 04 '12 at 20:41
  • That throws an exception: `"Property 'otherAttr' cannot be found on this object; make sure it exists and is settable."`. – ComFreek Nov 05 '12 at 19:52