我目前正在嘗試使用 Powershell 下載 XML 檔案,檔案中有一些節點的格式如下:
<BackendSystemSettings>
<Backend
a ="123"
b="ABC"
c="ABC123"/>
<Backend
a ="456"
b="DEF"
c="DEF456"/>
</BackendSystemSettings>
我想保持這種格式,但是當我保存 xml 檔案時,這個標簽中的所有元素都被放入 1 行:
<BackendSystemSettings>
<Backend a ="123" b="ABC" c="ABC123"/>
<Backend a ="456" b="DEF" c="DEF456"/>
</BackendSystemSettings>
以上只是一個例子,在我的真實資料中,它要長得多,所以當所有行合并為1行時,由于行太長,以后很難檢查。
我嘗試使用 Select-XML、PreserveWhitespace 但沒有任何效果。你們有什么建議嗎?
非常感謝!
uj5u.com熱心網友回復:
您可以定義更復雜的規則來說明如何通過XmlWriterSettings類保存 XML。
重要的是要注意輸入格式不會被保留。相反,輸出是根據該類提供的規則進行格式化的。
在您的情況下,我使用的規則是:
- Indent : 是否縮進元素
- NewLineOnAttributes:是否在單獨的行上寫入屬性(當 Indent 為 false 時無效)。
- OmitXmlDeclaration : 是否撰寫 XML 宣告。
在此處查看官方檔案以查看所有可用的規則及其作用。
現在,你想看到什么:
在單獨的行上撰寫每個屬性的 XML
# Note, I am purposefully using the non-desired output as an input.
$xml = [xml]@'
<BackendSystemSettings>
<Backend a ="123" b="ABC" c="ABC123"/>
<Backend a ="456" b="DEF" c="DEF456"/>
</BackendSystemSettings>
'@
Function Export-XML {
[CmdletBinding()]
Param($xml, $Path)
# XMLWriter Settings ... Where the magic happen
$settings = [system.Xml.XmlWriterSettings]::new()
# Use the parameters you need
$settings.OmitXmlDeclaration = $true
$settings.NewLineOnAttributes = $true
$settings.Indent = $true
$writer = [System.Xml.XmlWriter]::Create($Path, $settings)
$xml.Save($writer)
$Writer.Dispose()
}
# Do whatever modifications you wish to perform...
$xml.BackendSystemSettings.Backend[0].a = 'Modified !!!!'
# Here we call our new function to save the XML
Export-XML -xml $xml -Path 'C:\temp\test\71376785.xml'
結果輸出
<BackendSystemSettings>
<Backend
a="Modified !!!!"
b="ABC"
c="ABC123" />
<Backend
a="456"
b="DEF"
c="DEF456" />
</BackendSystemSettings>
參考:
XmlWriterSettings 類
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/439098.html
上一篇:在Azure自動化帳戶(powershell)中將字串轉換為日期時間
下一篇:使搜索運算式不貪婪
