在XML属性中包含&符号

时间:2012-11-04 19:57:04

标签: xml dom powershell html-entities xml-attribute

问题

我们要分配一个内容已包含"&等实体的属性。
在此示例中,我们希望title属性为Stack "Stacky" Overflow

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

但是这会变成下面的XML输出:

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


XmlElement.SetAttribute Method

的文档中甚至说明了这种行为
  

为了分配包含实体引用的属性值,   用户必须创建XmlAttribute节点加上任何XmlText和   XmlEntityReference个节点,构建适当的子树并使用   SetAttributeNode将其指定为属性的值。

3 个答案:

答案 0 :(得分:3)

解决方案

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

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

$elem.SetAttributeNode($elemAttr);

XML输出:

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

答案 1 :(得分:0)

PS> $xml.Site.Title = [System.Security.SecurityElement]::Escape('Stack "Stacky" Overflow')
PS> $xml.Site.Title

Stack &quot;Stacky&quot; Overflow

答案 2 :(得分:0)

不知道这是否有帮助

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