在 Powershell 中解析 XML 并获取所有 xsd 验证错误

问题描述 投票:0回答:1

我的目标是针对

xml
中的
xsd schema
文件验证
powershell 5.1
。到目前为止,我得到了以下代码。实际上它有效并告诉我错误。但问题是,只有第一个验证错误才会写入控制台。如果我修复了 xml 中的错误,再次运行脚本,它会显示下一个错误。

我做了很多研究,但我找不到让它运行并记录所有现有验证错误的方法。

你知道怎么回事吗?

$xmlPath = "C:\path\to\my\product.xml"
$xsdPath = "C:\path\to\my\product.xsd"
$targetNamespace = "myNAMESPACE"

function Test-XmlBySchema
{
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [Parameter(Mandatory)]
        [ValidateScript({ Test-Path -Path $_ })]
        [ValidatePattern('\.xml')]
        [string]$XmlFile,
        [Parameter(Mandatory)]
        [ValidateScript({ Test-Path -Path $_ })]
        [ValidatePattern('\.xsd')]
        [string]$SchemaPath
    )

    BEGIN {
    $failCount = 0
    $failureMessages = ""
    $fileName = ""
    }

    PROCESS {
        
        foreach($eR in $error ){
            try {
                [xml]$xml = Get-Content -Path $XmlFile -ErrorAction "SilentlyContinue"
                $xml.Schemas.Add($targetNamespace, $SchemaPath) | Out-Null
                $xml.Validate($null)
                Write-Verbose "Successfully validated $XmlFile against schema ($SchemaPath)"
            }
        
            catch {
                $err = $_.Exception.Message
                Write-Verbose "Failed to validate '$XmlFile' against schema '$SchemaPath' "
                Write-Verbose  $err
                
                #Write-Host "Script Error: $_.ScriptStackTrace"
                #$result = $false
            }

            finally {
                #result
                #failCount
                #handler to ensure we always close the reader sicne it locks files
                #$reader.Close()
               # $Error[0].exception.GetType().fullname
               $error.count
            }
        } # End of Loop
    }
}

Test-XmlBySchema -XmlFile $xmlPath -SchemaPath $xsdPath -Verbose –ErrorAction SilentlyContinue```
powershell xml-parsing xsd-validation powershell-5.1
1个回答
0
投票

我开始翻译了。这是我到目前为止得到的

$URL = 'http://www.contoso.com/books'
$xsdFilename = 'books.xsd'
$xxmFilename = 'books.xml'

Function booksSettingsValidationEventHandler
{
   param ([object] $sender, [System.Xml.Schema.ValidationEventArgs] $e)

   if($e.Severity -eq [System.Xml.Schema.XmlSeverityType]::Warning)
   {
       Console.Write("WARNING: ");
       Console.WriteLine($e.Message);
   }
   else
   {
      if ($e.Severity -eq [System.Xml.Schema.XmlSeverityType]::Error)
      {
         Write-Host 'ERROR'
         Write-Host $e.Message
      }
   }
}


$booksSettings = [System.Xml.XmlReaderSettings]::new();

$booksSettings.Schemas.Add($URL, $xsdFilename);
$booksSettings.ValidationType = [System.Xml.ValidationType]::Schema;


$booksSettings.ValidationEventHandler += booksSettingsValidationEventHandler;

$books = [System.Xml.XmlReader]::Create([string]$xmlFilename, [System.Xml.XmlReaderSettings]$booksSettings);

while ($books.Read()) {  }
© www.soinside.com 2019 - 2024. All rights reserved.