2012-11-04 47 views
2

問題

我們想要分配其內容已經包含了像"&實體的屬性。
在這個例子中,我們想要的標題屬性是Stack "Stacky" Overflow包含在一個XML的符號屬性

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

但是,這變成了下面這段XML輸出:

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


這種行爲甚至在有關XmlElement.SetAttribute Method的文檔中說明:

爲了分配包含實體引用的屬性值, 用戶必須創建一個XmlAttribute節點加上任何XmlTextXmlEntityReference節點,建立適當的子樹,並使用 SetAttributeNode將其指定爲一個屬性的值。

回答

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" /> 
+0

代替InnerXml,可以使用ATTR值: $ elemAttr.value =「Stack " Stacky "溢出」; – Atara

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

Stack &quot;Stacky&quot; Overflow 
+0

當然,這也是一個解決方案。但就我而言,我的字符串中有很多''的序列。我認爲我的解決方案在這種情況下更簡單。還有可能調用實體解碼函數(我不知道PS中的確切名稱)。 – ComFreek

+0

你有沒有試圖以簡單的方式設置它? '$ xml.Site.Title ='Stack " Stacky "溢出' –

+0

拋出一個異常:''Property'otherAttr'在這個對象上找不到,請確保它存在並且可以設置。 – ComFreek

0

不知道這是否有助於

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

確實解決了這個問題嗎? –