2017-03-15 40 views
1

我需要一個XML值設置爲換行符換碼如何將XML值設置爲轉義字符在PowerShell中

<Variable>Foo &#xA; Bar</Variable> 

我使用的是獲取內容,以創建一個XML對象,並試圖分配變量使用下面的方法

$qux = $("Foo &#xA; Bar") 
$xml = [xml](Get-Content $xmlpath) 

$xml.Variable = $qux 

$xml.Save($tlpath) 
$xml.Close 

我使用代替& &放試過,用單引號和反斜線,我似乎無法防止代碼轉換&到&放大器並吐出以下xml

<Variable>Foo &amp;#xA; Bar</Variable> 

什麼是避開PowerShell轉換轉義字符的最佳方式是什麼?

+0

淨XML類[保存\ n的實際的新行內的文本節點(https://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.newlinehandling(v = vs.110)的.aspx)。爲什麼你需要它作爲一個實體? – wOxxOm

回答

1

分配一個正常多行字符串:

$xml.Variable = "Foo`nBar" 

或訪問變量作爲XML節點和分配哪些將被改造成正常換行字符的XML字符串:

$xml['Variable'].innerXml = "Foo&#xA;Bar" 

.NET框架XML類將新行字符保存爲實際新行inside text nodes,並將其作爲內部屬性時的實體。這意味着我們需要寫它之前進行後處理XML輸出:

$xml = [xml]::new() 
$xml.Load('r:\1.xml') 

$xml.Variable = "Foo`nBar" 

# encode &#xD; inside text nodes and both &#xA; &#xD; inside attributes 
$xmlSettings = [Xml.XmlWriterSettings]::new() 
$xmlSettings.NewLineHandling = [Xml.NewLineHandling]::Entitize 
$sb = [Text.StringBuilder]::new() 
$xmlWriter = [System.Xml.XmlWriter]::Create($sb, $xmlSettings) 
$xml.Save($xmlWriter) 

$sb.ToString().Replace("`n", '&#xA;') | Out-File r:\2.xml -Encoding utf8 

注:PowerShell 2.0中,而不是[some.class]::new()使用New-Object some.class

+0

當我嘗試執行此操作並通過.innerXml設置變量不能工作時,我收到了「無法找到類型XML.XMLWriterSettings」。我很不幸地使用了 –

+0

我正在使用PowerShell 5.1和新的NET框架。那麼,你總是可以簡單地讀取xml文件作爲文本,並替換新行'(get-content 2.xml) - 加入' '| out-file ......' – wOxxOm

+0

解決了它。謝謝! –

相關問題