[英]Powershell adding characters in XML
I've got an XML file that's something like this:我有一个类似于这样的 XML 文件:
<globalConfigs>
<!-- some settings -->
<globalConfig key="currency" value="£" />
</globalConfigs>
And I've got some Powershell which is manipulating it along the lines of this:我有一些 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);
}
Now this works as expected in that it adds the new key.现在这按预期工作,因为它添加了新密钥。 But the resulting xml adds an extra character in before the pound sign:
但是生成的 xml 在井号之前添加了一个额外的字符:
<globalConfigs>
<!-- some settings -->
<globalConfig key="currency" value="£" />
<globalConfig key="currencyCode" value="GBP" />
</globalConfigs>
What is causing this extra character?是什么导致了这个额外的字符? It appears to be intermittent, but it's added more often than not.
它似乎是间歇性的,但它经常被添加。
Your XML contains a non-ASCII character without proper encoding.您的 XML 包含一个没有正确编码的非 ASCII 字符。 Either encode the character as an entity reference (
£
), or add a declaration to your XML data:将字符编码为实体引用 (
£
),或向 XML 数据添加声明:
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)
}
I managed to fix this - the issue is in the Get-Content cmdlet.我设法解决了这个问题 - 问题出在 Get-Content cmdlet 中。 If I change the line that loads the XML to this:
如果我将加载 XML 的行更改为:
[xml]$config = Get-Content $filePath -Encoding UTF8;
then I don't get the unwanted character in the output.那么我在输出中没有得到不需要的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.