【问题标题】:Powershell - xmlPowershell - xml
【发布时间】:2017-10-25 10:28:17
【问题描述】:

我有一个输入 XML 文件,其中包含各种字符的普通 HTML 名称,例如双引号 = "

<Notes>Double Quote &quot; Single Quote &pos; Ampersand &amp;</Notes>

之前

<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
  <OrganisationUnitsRow num="8">
    <OrganisationId>ACME24/7HOME</OrganisationId>
    <OrganisationName>ACME LTD</OrganisationName>
    <Notes>Double Quote &quot; Single Quote &pos; Ampersand &amp; </Notes>
    <Sector>P</Sector>
    <SectorDesc>Private Private &amp; Voluntary</SectorDesc>
  </OrganisationUnitsRow>
</OrganisationUnits>

之后

<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
  <OrganisationUnitsRow num="8">
    <OrganisationId>ACME24/7HOME</OrganisationId>
    <OrganisationName>ACME LTD</OrganisationName>
    <Notes>Double Quote " Single Quote ' Ampersand &</Notes>
    <Sector>P</Sector>
    <SectorDesc>Private Private & Voluntary</SectorDesc>
  </OrganisationUnitsRow>
</OrganisationUnits>

我将文件当作 XML 处理,它可以正常处理,没什么特别的。

$xml = [xml](Get-Content $path\$File)
foreach ($CMCAddressesRow in $xml.OrganisationUnits.OrganisationUnitsRow) {
    blah
    blah
}
$xml.Save("$path\$File")

保存输出后,所有 HTML 代码(如 &amp;quot;)将替换为 "。 如何保留原始 HTML &amp;quot; 字符?更重要的是为什么会这样。

【问题讨论】:

  • XML文件的第6行应该有&amp;apos吗?
  • System.Net.WebUtility.HtmlDecode 和 System.Net.WebUtility.HtmlEncode
  • 看来更换了"当文件被读取为 [xml] 时, &apos 已经发生。
  • 这是&amp;apos;,而不是&amp;pos;,并且&amp;amp; 保留在输出中。发布示例时,请确保它们是正确的。创建一个minimal reproducible example 并复制/粘贴它。不要凭记忆打字。不要胡编乱造。

标签: html xml powershell replace character


【解决方案1】:

您所指的是“字符实体”。 PowerShell 在导入时转换它们,因此您可以使用这些实体表示的实际字符,并在导出时仅转换必须在 XML 文件中编码的内容。引号字符不需要在节点值中编码,因此它们不会在导出时进行编码。

【讨论】:

  • 抱歉打错了——我的错。我发现通过使用 [System.Security.SecurityElement]::Escape($var) 我可以做我一直在寻找的事情。 $dbl = '"' (Get-Content $path\$InFile) | Foreach-Object {$_ -replace '(?is)(?.*?)"(?=.*? Notes>)', [System.Security.SecurityElement]::Escape($dbl) } | Set-Content $path\$InFile 这将采用 " 双引号并将其替换为 " - 非常粗略,但我相信它可以改进。
  • 确实如此。这些示例可以在W3C Markup Validation Service 进行验证。
猜你喜欢
  • 2011-01-11
  • 2014-02-20
  • 2011-12-29
  • 2019-03-28
  • 1970-01-01
  • 2016-05-13
  • 2021-12-13
  • 2012-04-13
  • 1970-01-01
相关资源
最近更新 更多