Как проверить xsd схему на ошибки

В данном разделе описаны способы проверки XML-файла по XSD-схеме. Сделать это можно разными способами, существует много программ для этих целей. По XSD-схеме, например, проверяет программа Tester, но она только показывает ошибки и не дает их исправить. Для большего удобства лучше использовать специализированные редакторы такие, как XMLPad или MS Visual Studio.

MS Visual Studio является спецаилизированным инструментом для программистов, обладающим огромным функционалом. Работа с XML и автоматическая проверка по XSD – лишь одна из множества функций среды разработки. MS Visual Studio 15 можно скачать бесплатно с официального сайта: https://www.visualstudio.com/ru-ru/products/visual-studio-community-vs.

XMLPad — многофункциональный специализированный XML редактор. XMLPad обладает богатым функционалом, поддерживает XPath, возможность удалять целые блоки тегов, смену кодировок, проверку валидности и т.д. XMLPad доступен для бесплатного использования на сайте: http://xmlpad-mobile.com.

Совет

XMLPad уступает по удобству и возможностям MS Visual Studio, но если вы не являетесь программистом и у вас не установлена MS Visual Studio, лучше воспользоваться XMLPad.

Примечание

Перед проверкой файлов необходимо предварительно скачать файлы XSD-схем. Скачать XSD-схемы можно с официальных сайтов контролирующих органов. В качестве примера взята декларация по НДС, скачать XSD-схему для нее можно с сайта Справочник налоговой и бухгалтерской отчетности.

Проверка по XSD-схеме в XMLPad¶

  1. Откройте XML-файл, который требуется проверить в XMLPad File > Open.

  1. Чтобы проверить файл по заданной XSD-схеме, его надо с ней ассоциировать. Перейдите в меню XML > Assign Schema/DTD.

  1. Выберите W3C Schema и нажмите Browse, затем выберите XSD-схему для проверки.

  1. После того, как XSD-схема ассоциирована, нажмите F7 или XML > Validate, чтобы проверить файл. В нижней части окна будут выведены ошибки, нажав на которые можно подсветить строку, в которой они находятся.

Совет

Для удобства отображения можно включить переносы строк Edit > Word Wrap.

Проверка по XSD-схеме в MS Visual Studio¶

  1. Откройте XML-файл, который требуется проверить в MS Visual Studio Файл > Открыть > Файл.

  1. Чтобы проверить файл по заданной XSD-схеме, его надо с ней ассоциировать. Перейдите в меню XML-код > Схемы….

  1. Нажмите Добавить и выберите файл XSD-схемы.

Проверка на соответсвие XSD-схеме будет осуществляться автоматически на лету. Внизу в окне Списка ошибок будет отображаться список ошибок. При нажатии на ошибку, она будет подсвечена в редакторе.

Совет

Добавить окно Списка ошибок можно через Вид > Списка ошибок.

I’m writing an XML schema (an XSD) to describe the format our partners should send us data in.

And I’m having a hard time finding a tool that can validate the XSD schema file that I have written.

The best way I have found so far is to first write an example input XML file and then try to validate that with the XSD. But that doesn’t feel like a best practice maneuver.

So, how should I validate an XML schema?

DavidRR's user avatar

DavidRR

18.3k25 gold badges109 silver badges191 bronze badges

asked Jul 29, 2009 at 12:36

Alexander Kjäll's user avatar

Alexander KjällAlexander Kjäll

4,2663 gold badges33 silver badges57 bronze badges

6

The W3C has a online validator for XML Schemas at http://www.w3.org/2001/03/webdata/xsv. Since W3C is the source of the XML Schema spec, their validator should be trustworthy.

answered Jun 10, 2010 at 13:08

Matt Lavin's user avatar

5

If this is a short-term thing, you could use an evaluation copy of a tool like Stylus Studio.

If it’s long-term maintenance, you might want to consider purchasing an XML schema editor like Stylus, or Oxygen or Altova.

You didn’t specify the source language, but it’s only a few lines of code to write a schema validator in Java or .Net.

Christopher Grigg's user avatar

answered Jul 29, 2009 at 12:44

lavinio's user avatar

laviniolavinio

24k5 gold badges55 silver badges71 bronze badges

4

cd /the/dir/with/your/schema
curl -O https://www.w3.org/2012/04/XMLSchema.xsd
xmllint.exe --noout --schema XMLSchema.xsd <your schema>

In *nix (including git-bash or similar on Windows), if the schema is valid then $? == 0 else $? == 1. I’m sure there is some powershell equivalent …

This came from a comment by @AlexanderKjäll to an answer by @lavinio elsewhere here. I added my own comment to say @AlexanderKjäll should add this as an answer. However (for me atleast), it wasn’t quite correct since it won’t work using the remote file URI. And thus my answer. If you upvote this could you please upvote their comment.

answered Feb 26, 2018 at 3:22

HankCa's user avatar

HankCaHankCa

9,1398 gold badges62 silver badges83 bronze badges

So, how should I validate an XML schema (XSD)?

The question you ask is a good one. Just «winging it» is likely to get you in trouble. From the Wikipedia article XML Schema Editor (emphasis mine):

The [W3C XML Schema] standard is versatile, allowing for programming
concepts such as inheritance and type creation, but it is complex.
The standard itself is highly technical and published in 3 different parts, making it difficult to understand without
committing large amounts of time
.

So, given the complexity of the W3C XML Schema standard, how do you ensure that a schema that you create complies with that standard? From the same Wikipedia article:

The problems users face when working with the XSD standard can be
mitigated with the use of graphical editing tools. Although any
text-based editor can be used to edit an XML Schema, a graphical
editor offers advantages; allowing the structure of the document to be
viewed graphically and edited with validation support, entry helpers
and other useful features.

At the bottom of that Wikipedia article you’ll find a list of XML schema editors, some of which are licensed as «free software.»

answered Aug 6, 2015 at 14:00

DavidRR's user avatar

DavidRRDavidRR

18.3k25 gold badges109 silver badges191 bronze badges

  • Video Tutorial




    VIEW TUTORIAL

    Data Mapper - XML to JSON

    Data Mapper — XML to JSON


  • Free Online XML Tools

    1. XML Formatter
    2. XML Validator
    3. XML Validator (XSD)
    4. XML Validator (RelaxNG)
    5. XML Validator (Schematron)
    6. XML to XSD
    7. XSD to XML
  • Free Online Code Generation Tools

    1. XSD to C#
    2. XSD to VB.Net
  • Free Online JSON Tools

    1. JSON Formatter
    2. JSON Validator
    3. JSON Validator
    4. JSON to JSON Schema
    5. JSON Schema to JSON

  • XML Schema Tutorials

    • Elements and Attributes
    • Conventions and Recommendations
    • Extending Existing Types
    • Namespaces
    • Groups and Any Types

Validates an XML document using an XSD schema.

Download Liquid Studio
Access the online tools directly from your desktop.
Download Free Liquid Studio Community Edition Now!

XML data to validate

XML schema (XSD) data

WORKING

Document Valid

Errors

Severity Location Filename Message
       

Please Note:
All data is stored in our log files and periodically deleted, if you have sensitive data, please Download the Free Liquid Studio Community Edition and use the tools directly from your desktop.

More Editors and Tools




FEATURE DETAILS

Graphical XSD Editor

Graphical XML Schema Editor(XSD)




FEATURE DETAILS

Graphical XML Editor

Graphical XML Editor




FEATURE DETAILS

Graphical JSON Schema Editor

Graphical JSON Schema Editor




FEATURE DETAILS

JSON Editor

JSON Editor




FEATURE DETAILS

Liquid Data Mapper

Data Mapper




FEATURE DETAILS

Liquid Data Diff Viewer

Data Diff Viewer




FEATURE DETAILS

XML Data Binder

XML Data Binder (C++, Java, VB6)




FEATURE DETAILS

XML Objects

XML Objects (C#, VB .Net)

Try all the features of Liquid Studio
Download Free Trial Now

After some research, I think the best answer is Xerces, as it implements all of XSD, is cross-platform and widely used. I’ve created a small Java project on github to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux.

There is also a C++ version of Xerces available if you’d rather use that. The StdInParse utility can be used to call it from the command line. Also, a commenter below points to this more complete wrapper utility.

You could also use xmllint, which is part of libxml. You may well already have it installed. Example usage:

xmllint --noout --schema XSD_FILE XML_FILE

One problem is that libxml doesn’t implement all of the specification, so you may run into issues :(

Alternatively, if you are on Windows, you can use msxml, but you will need some sort of wrapper to call it, such as the GUI one described in this DDJ article. However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in Nate’s answer) or XML Notepad 2007 as suggested by SteveC (there are also several commercial editors which I won’t mention here).

Finally, you’ll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools.

UPDATE: I’ve expanded on this in a blog post.

Extensible Markup Language (XML) schema express shared vocabulary and allows machines to execute rules made by human beings.

They provide a method of defining the structure, semantics, and content of XML documents.
A Well-Formed and well-structured XML document means that it has proper XML syntax and rules. 

Validating XML Documents

A valid XML document is «Exquisite», and also adapts to the rules and regulations of a «Document Type Definition (DTD)», XML Schema, or other types of schema that determine the construction of an XML document.

The problem is that errors may be introduced when creating XML documents.
Handling large projects or a large number of files will increase the probability of errors.

Identifying and resolving errors in a project is time-consuming and frustrating sometimes.
Fortunately, the features provided by this XML XSD validator make it quicker and easier to recognize mistakes.

Validating against W3C XML Schemas

This XSD validator tool provides the latest version of the Java API for XML Processing to verify files against XML Schemas.

By using this online xml schema validator and checker, you can check the validity of XML against XSD quite easily.

How this XSD validator work?

All you have to do is just paste the XML and click on “Check XSD validity” button.

In XML Schema Definition (XSD), we can verify:

  • Checking the schema in its value
  • The same name field by checking its data type
  • Maximum length
  • Minimum length

Understanding XSD

A simple element in XSD consists of the text of various data types, like Boolean value, date, string, or any custom type. 

It can be restricted to maintain the consistency of values. A complex element with specific element values is called an attribute. 

When specifying attributes, an element is considered to be a complex element. When only one element is needed to be validated, we can validate it under XSD tag xs:simpleType.

In this case, the validations are more specific to the type of a specific element.

However, when a group or series of elements are to be verified, we can specify it under xs:complexType.

Here, XSD verifies all child components under a parent element, sequentially.

For any type of XSD file, the XML declaration statement, together with namespace information, is required. 

An extensible markup language namespace is a collection of names that can be used as elements or attributes in XML files. 

In order to avoid conflicts between elements with the same name, it uniquely defines the names of elements on the network.

We can validate the outermost element, child elements, sub-child elements, event type, and event timing through this sort of process.

Понравилась статья? Поделить с друзьями:
  • Как проверить ssd nvme на наличие ошибок
  • Как проверить wordpress на ошибки
  • Как проверить dll файлы на ошибки
  • Как проверить ssd kingston на наличие ошибок
  • Как проверить windows 7 на ошибки и исправить