繁体   English   中英

Powershell 在 XML 中添加字符

[英]Powershell adding characters in XML

我有一个类似于这样的 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>

是什么导致了这个额外的字符? 它似乎是间歇性的,但它经常被添加。

您的 XML 包含一个没有正确编码的非 ASCII 字符。 将字符编码为实体引用 ( &#163; ),或向 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)
}

我设法解决了这个问题 - 问题出在 Get-Content cmdlet 中。 如果我将加载 XML 的行更改为:

[xml]$config = Get-Content $filePath -Encoding UTF8;

那么我在输出中没有得到不需要的字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM