我有一个类似这样的XML文件:
<globalConfigs>
<!-- some settings -->
<globalConfig key="currency" value="£" />
</globalConfigs>
我有一些Powershell正在按照以下方式操纵它:
function Update-Config ($filePath, $siteName) {
[xml]$config = Get-Content $filePath;
$newNode = $config.CreateElement("globalConfig");
$keyAttribute = $config.CreateAttribute("key");
$keyAttribute.Value = "currencyCode";
$newNode.Attributes.Append($keyAttribute);
$valAttribute = $config.CreateAttribute("value");
$valAttribute.Value = "GBP";
$newNode.Attributes.Append($valAttribute);
$config.globalConfigs.AppendChild($newNode);
Write-Log "Added config node to site.";
$config.Save($filePath);
}
现在这可以正常工作,因为它添加了新密钥。但是得到的xml在井号前添加了一个额外的字符:
<globalConfigs>
<!-- some settings -->
<globalConfig key="currency" value="£" />
<globalConfig key="currencyCode" value="GBP" />
</globalConfigs>
造成这个额外角色的原因是什么?它似乎是断断续续的,但它经常被添加。
答案 0 :(得分:1)
Your XML contains a non-ASCII character without proper encoding. Either encode the character as an entity reference (£
), or add a declaration to your XML data:
function Update-Config ($filePath, $siteName) {
[xml]$config = Get-Content $filePath;
$newNode = $config.CreateElement("globalConfig");
$keyAttribute = $config.CreateAttribute("key");
$keyAttribute.Value = "currencyCode";
$newNode.Attributes.Append($keyAttribute);
$valAttribute = $config.CreateAttribute("value");
$valAttribute.Value = "GBP";
$newNode.Attributes.Append($valAttribute);
$config.globalConfigs.AppendChild($newNode)
Write-Log "Added config node to site."
$declaration = $config.CreateXmlDeclaration('1.0', 'utf-8', $null)
[void]$config.InsertBefore($declaration, $config.DocumentElement)
$config.Save($filePath)
}
答案 1 :(得分:0)
我设法解决了这个问题 - 问题出在Get-Content cmdlet中。如果我将加载XML的行更改为:
[xml]$config = Get-Content $filePath -Encoding UTF8;
然后我不会在输出中得到不需要的字符。