【问题标题】:Remove XML encoding information with PowerShell使用 PowerShell 删除 XML 编码信息
【发布时间】:2017-08-25 02:28:53
【问题描述】:

我目前正在使用 TFS PowerTools 在 PowerShell 中运行查询并将结果导出为 XML 文件。然后我想将该 XML 文件导入 Alteryx 以进行进一步处理。当 TFS PT 导出 XML 文件时,它会将以下标头放在顶部:

<?xml version="1.0" encoding="utf-8"?>

但是 Alteryx 不喜欢这样并且拒绝阅读文档,除非编码信息被删除。有没有办法可以使用 PowerShell 删除编码信息,所以它只显示:

提前感谢您的帮助。

【问题讨论】:

    标签: xml powershell encoding


    【解决方案1】:

    是的,你可以:

    $doc = New-Object xml
    $doc.Load((Resolve-Path ".\path\to\doc.xml").ProviderPath)
    if($doc.FirstChild.NodeType -eq 'XmlDeclaration')
    {
        $doc.FirstChild.Encoding = $null
    }
    $doc.Save((Resolve-Path ".\path\to\doc.xml").ProviderPath)
    

    【讨论】:

    • 感谢您的快速回复!我将您的代码插入到我的脚本中并更改了文件路径,但是当我运行脚本时出现以下错误:
    • 使用“1”参数调用“Load”时出现异常:“'.',十六进制值 0x00,是无效字符。第 2 行,位置 1。”
    • 在 C:\Users\RunQuery.ps1:29 char:1 + $doc.Load((Resolve-Path ".\workItems.xml").ProviderPath) + CategoryInfo : NotSpecified: (: ) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException 使用“1”参数调用“保存”的异常:“无效的 XML 文档。该文档没有根元素。”在 C:\Users\RunQuery.ps1:34 char:1 + $doc.Save((Resolve-Path ".\workItems.xml").ProviderPath) + + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException
    • @camruny 听起来您的 xml 文档格式不正确(包含无效的 unicode 字符)。请看this answer
    • 谢谢!这删除了编码信息,我添加了您附加的代码以删除无效字符。似乎连字符现在导致了这个问题。知道如何修改您链接的代码以包含连字符。再次感谢您的所有帮助!
    【解决方案2】:

    这将起作用,但是 xml 文件不再有效。

    $xml = get-content $xmlfile | Out-String
    $xml = $xml.replace('<?xml version="1.0" encoding="utf-8"?>',"") #removes text
    $xml | out-file $xmlfile #outputs text in file
    

    【讨论】:

    • 虽然code may answer the question,但提供有关为什么和/或如何此代码回答问题的附加上下文可提高其长期价值。
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多