2017-01-24 9 views
0

мне нужно проверить XML против XSD с помощью Powershell скрипт с предупреждениями о дополнительных атрибутах и ​​т.д. Например, мой XSD:Проверка дополнительных атрибутов против XSD-схемы в PowerShell

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 


    <xs:complexType name="LocalizedValue"> 
    <xs:attribute name="Lang" type="xs:string" use="required"> 
     <xs:annotation> 
     <xs:documentation>Language Code</xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    <xs:attribute name="Name" type="xs:string" use="required"> 
     <xs:annotation> 
     <xs:documentation>District Typr</xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    <xs:attribute name="ShortName" type="xs:string" use="optional"> 
     <xs:annotation> 
     <xs:documentation>Аbbreviation</xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    </xs:complexType> 

    <xs:complexType name="DistrictType"> 
    <xs:sequence> 
     <xs:element name="Localizations" minOccurs="1" maxOccurs="1"> 
     <xs:complexType> 
      <xs:sequence> 
      <xs:element name="Localization" type="LocalizedValue" minOccurs="1" maxOccurs="unbounded"> 
       <xs:annotation> 
       <xs:documentation>Local attributes</xs:documentation> 
       </xs:annotation> 
      </xs:element> 
      </xs:sequence> 
     </xs:complexType> 
     </xs:element> 
     <xs:element name="Branches"> 
     <xs:complexType> 
      <xs:sequence> 
      <xs:element name="Branch" minOccurs="0" maxOccurs="unbounded"> 
       <xs:complexType> 
       <xs:attribute name="Code" type="xs:int" use="required"> 
        <xs:annotation> 
        <xs:documentation>Branch Code</xs:documentation> 
        </xs:annotation> 
       </xs:attribute> 
       </xs:complexType> 
      </xs:element> 
      </xs:sequence> 
     </xs:complexType> 
     </xs:element> 
    </xs:sequence> 
    <xs:attribute name="Code" type="xs:int" use="required"> 
     <xs:annotation> 
     <xs:documentation>Dictionary code</xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    <xs:attribute name="GroupCode" type="xs:int" use="optional"> 
     <xs:annotation> 
     <xs:documentation>Another Code</xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    <xs:attribute name="IsDeleted" type="xs:boolean" use="optional" default="false"> 
     <xs:annotation> 
     <xs:documentation> 
     documentation 
     </xs:documentation> 
     </xs:annotation> 
    </xs:attribute> 
    </xs:complexType> 

    <xs:element name="DistrictType" type="DistrictType"> 
    <xs:annotation> 
     <xs:documentation>documentation</xs:documentation> 
    </xs:annotation> 
    </xs:element> 
</xs:schema> 

И XML:

<DistrictType Code="1" IsDeleted="false" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./../Schema/flowGeoClassifier.DistrictType.xsd"> 
    <Localizations> 
    <Localization Lang="ru" Name="район" ShortName="р-н" /> 
    </Localizations> 
    <Branches> 
    <Branch Code="1" /> 
    </Branches> 
    <Countries> 
    <Country Code="1" /> 
    <Country Code="483647" /> 
    <Country Code="2147483647" /> 
    </Countries> 
</DistrictType> 

мне нужно, чтобы получить какое-то сообщение подобное:

Предупреждение: Необязательный атрибут "GroupCode" отсутствует.

Я использую Powershell скрипт для проверки:

$XmlFile = Get-Item($xmlFileName) 
    # Perform the XSD Validation 
    $readerSettings = New-Object -TypeName System.Xml.XmlReaderSettings 
    $readerSettings.Schemas.Add($compiledSchema) 
    $readerSettings.ValidationType = [System.Xml.ValidationType]::Schema 
    $readerSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation 
    $readerSettings.add_ValidationEventHandler(
    { 
     # Triggered each time an error is found in the XML file 
     Write-Host $("ERROR line $($_.exception.LineNumber) position $($_.exception.LinePosition) in '$xmlFileName': " + $_.Message) -ForegroundColor Red 
     $script:errorCount++ 
    }); 
    $reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $readerSettings) 
    while ($reader.Read()) { } 
    $reader.Close() 

Имеет ValidationEventHandler проверки дополнительных атрибутов с помощью стандартного methodes?

ответ

0

Почему бы не создать вариант схемы, в которой атрибуты являются обязательными, а затем проверить на это?

Схемы черно-белые, все либо имеет силу, либо нет: там не так много места для предупреждений. Но вам не обязательно использовать одну и ту же схему все время, вы можете проверить ее на разных этапах, используя схемы с разной степенью строгости.

0

XmlReader считает, что отсутствующий необязательный атрибут отлично действует, поэтому не будет возникать ошибка (или предупреждение).

Единственный способ получить эту информацию самостоятельно - это проверить их вручную. Вы можете сделать это довольно легко, прочитав свой документ в XmlDocument, а затем running XPath запросов для проверки.

+0

Thank's! Но этот метод не подходит для моего случая. –