【问题标题】:VERY large XML files in PowershellPowershell 中非常大的 XML 文件
【发布时间】:2018-06-14 14:23:50
【问题描述】:

对于非常大的文本文件,我们可以选择使用 StreamReader 和 StreamWriter,然后允许逐行查找/替换。但是,我有一个 XML 文件,我需要在其中进行查找/替换,并进行更多控制,例如查找/替换特定节点中的值,该节点是具有特定属性和值的另一个节点的子节点。因此,尝试逐行解析相当复杂,并且在使用 XML 文档时超级容易处理。但是,我的文件正在推送 500 MB 和 1200 万行,并且仅加载文件需要很长时间。 XML 是否有 .NET 等价物?或者我是否仅限于使用本地 PowerShell,会导致相关的性能下降?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    您可能想查看What is the difference between SAX and DOM? 以获取有关解析 XML 的替代方法的信息。

    SAX 可能是您的好方法。

    PowerShell and .Net itself don't have a native SAX parser,但XmlReader class 可能对你有用。

    MSDN Docs 上的示例看起来,它似乎没有做任何太疯狂的事情或使用 PowerShell 中乏味/困难的功能。

    这是他们的 C# 示例:

    // Create a validating XmlReader object. The schema 
    // provides the necessary type information.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add("urn:empl-hire", "hireDate.xsd");
    using (XmlReader reader = XmlReader.Create("hireDate.xml", settings)) {
    
      // Move to the hire-date element.
      reader.MoveToContent();
      reader.ReadToDescendant("hire-date");
    
      // Return the hire-date as a DateTime object.
      DateTime hireDate = reader.ReadElementContentAsDateTime();
      Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6));
    }
    

    这是一个我根本懒得测试的 PowerShell 端口(抱歉):

    # Create a validating XmlReader object. The schema 
    # provides the necessary type information.
    
    $settings = New-Object System.Xml.XmlReaderSettings
    $settings.ValidationType = [System.Xml.ValidationType]::Schema
    $settings.Schemas.Add("urn:empl-hire", "hireDate.xsd") 
    # see their page for example XML/XSD
    
    try {
        $reader = [System.Xml.XmlReader]::Create("hireDate.xml", $settings)
    
        # Move to the hire-date element.
        $reader.MoveToContent();
        $reader.ReadToDescendant("hire-date");
    
        # Return the hire-date as a DateTime object.
        $hireDate = $reader.ReadElementContentAsDateTime()
        "Six Month Review Date: {0}" -f $hireDate.AddMonths(6) | Write-Verbose -Verbose
    } finally {
        $reader.Dispose()
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 2013-02-28
      • 2011-03-04
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      相关资源
      最近更新 更多