【问题标题】:How can I convert XML to UTF-8 and retain header如何将 XML 转换为 UTF-8 并保留标头
【发布时间】:2019-07-19 01:00:46
【问题描述】:

我正在尝试将 XML 转换为 UTF-8 并为转换后的文件创建一个新目录。

使用下面的代码成功地创建了 UTF-8 XML 文件,但是它忽略了

<!DOCTYPE dmodule[
!ENTITY % ISOEntities PUBLIC "ISO 8879-1986//ENTITIES ISO Character Entities 20030531//EN//XML" "http://www.s1000d.org/S1000D_4-0-1/ent/ISOEntities" %ISOEntities;
]>

这是我们需要的,因为信息是为图像放置的。

$files = Get-ChildItem "C:\source\*.xml"
$output = "C:\changed\"
foreach ($file in $files) {
    [System.Xml.XmlDocument]$doc = New-Object System.Xml.XmlDocument;
    $doc.set_PreserveWhiteSpace($true);
    $doc.Load($file);

    $root = $doc.get_DocumentElement();
    $xml = $root.Get-Content $file;
    $xml = '<?xml version="1.0" encoding="utf-8"?>' + $xml

    $newFile = $output + $file.Name
    Set-Content -Encoding UTF8 $newFile $xml;
}

预期结果是保留整个文档或至少在转换后获取并添加标题数据。

【问题讨论】:

  • xml文件长什么样子?
  • Doctype 遵循标题 ,如您所见,我正在替换它,并且实体转换后的所有内容都很好。只需要包含此部分或获取内容并将其复制到背面即可。

标签: xml powershell


【解决方案1】:

好的,这是我的例子。

<!DOCTYPE note SYSTEM "Note.dtd"[]>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

在开头添加一行并保存为utf8。添加它的方式,它变成了一个字符串,而不是一个字符串数组。实际上这会起作用,但它会在文件的一行中。

$xml = get-content $file
$xml = '<?xml version="1.0" encoding="utf-8"?>',$xml
set-content $newfile $xml -Encoding UTF8

请注意,我不会像这样丢失 doctype 标签。你不需要这样做。

$xml = [xml](get-content $file)
$xml.save($file)

以这种方式加载和保存也会根据 xml 标签改变编码。

【讨论】:

  • 谢谢你,虽然我不是很关注,你是说在 foreach 循环的开头添加这一行吗?另外,我假设这应该只是 $file 而不是“file.xml”?
  • 我更改了答案以匹配您的变量。
  • 实际上,当我使用你的 doctype 标签时,我得到一个错误。 “未找到预期的 DTD 标记。第 3 行,位置 1。”
  • 不用担心,您的回答很有帮助。谢谢。
猜你喜欢
  • 2015-04-17
  • 2015-09-19
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2014-02-02
  • 2015-04-13
  • 2011-09-14
  • 1970-01-01
相关资源
最近更新 更多