Как создать xml по xsd схеме
Перейти к содержимому

Как создать xml по xsd схеме

  • автор:

Name already in use

visualstudio-docs / docs / xml-tools / how-to-create-an-xml-document-based-on-an-xsd-schema.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

How to: Create an XML document based on an XSD schema

The Generate Sample XML feature generates a sample XML file based on your XML Schema (XSD) file.

You can use this option for the following scenarios:

To understand the use of various constructs in your schema.

To confirm that the schema does what it is intended to do.

The Generate Sample XML feature is only available on global elements, and requires a valid XML schema set.

This feature typically generates valid XML documents. However, if the schema contains one or more of the following, the sample might not be valid:

The xs:key , xs:keyref , and xs:unique identity constraints.

Enumerations of the xs:QName type.

xs:ENTITY , xs:ENTITIES , and xs:NOTATION types.

Also, note that xs:base64Binary content will be generated only if enumerations occur in the schema for that type.

To generate an XML instance document based on the XSD file

In the XML Schema Explorer, right-click the PurchaseOrder global element, and then select Generate Sample XML.

When you select this option, the PurchaseOrder.xml file with the following sample XML content will be generated and opened in the XML editor:

generate xml from xsd [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

Closed 8 years ago .

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

Is there an IDE out there that can generate XML from XSD? Not Oxygen or XmlSpy, they are too expensive for me. command line based is ofcourse the preferred method!

8 Answers 8

The Netbeans IDE has a wizard for generating XML documents from an XSD schema. A nice thing is that you can also ask it to generate optional and repeating elements too.

You can do it in the Eclipse Web Tools (included in the Eclipse IDE for Java EE Developers).

Note that soon after this answer was originally posted, Apache XMLBeans was retired. As such, I cannot recommend it anymore. Anyway, I am still of the opinion that it had good command line support for generating example xsd:s, but a new release haven’t been done in well over 2 years at time of writing.

command line based is ofcourse the preferred method!

In my opinion xsd2inst in the Apache XMLBeans is a very good tool for this. It is command line based and ships with binaries for Windows and Unix/Linux.

It is really simple to use too:

xsd2inst schemafile.xsd -name globalElementName

It generates the output directly to the console and can of course easily be piped to a file.

Is there an IDE out there that can generate XML from XSD?

IntelliJ Idea has the same functionality if using an IDE is prefered, even in the community edition. Just right click inside the xsd document and select Generate Instance Document From Schema, then select the root node.

C# Разработка

Итак, что же мы будем делать, для того, что бы научиться штамповать XML на основе вашего эталона? Опишу всё по порядку.

Имеется:
Какой то XML (xmlfile.xml), сохраненный в текстовом формате в файл. Ниже приведу текст:

  1. Сначала используя утилиту XSD.exe, либо воспользовавшись онлайн сервисами (искать «xml to xsd» один из них www.freeformatter.com/xsd-generator.html), мы будем создавать из имеющейся XML ее примитивное XSD описание. На выходе мы будем иметь полностью, автоматическим образом, созданный output.xsd файл, который уже подходит к использованию но может быть не полным.
  2. Далее, на основе output.xsd, будут созданы классы на языке C# xmlclass.cs. После чего, мы добавляем его в наш проект. Создавать класс можно используя XSD.exe, либо xsd2code утилитой, или же любым онлайн сервисом.
  3. Теперь мы готовы использовать классы файла xmlclass.cs. Поэтому создадим и наполним данными экземпляры xmlclass, а потом, используя процесс сериализации, будем преобразовывать объекты в XML строку, и после чего сохраним ее в новый файл. Тем самым получим XML на основе имеющегося.

Шаг 1. Создание XSD из XML.

  1. Утилита xsd.exe — создатель Microsoft.
  2. Утилита xsd2code.exe — стороннее приложение, которое умеет все тоже самое, что и xsd.exe, но доступно для скачивания напрямую (на данный момент стала платной с Trial периодом).
  3. Использование любых онлайн сервисов.

— Ссылка для скачивания и установки одного из SDK:
Windows SDK for Windows 7 and .NET Framework 4.

— Далее перейдя в папку:
C:\Program Files (x86)\Microsoft SDKs\Windows>

— Воспользуемся поиском, и найдем файл xsd.exe, после чего (что бы упростить себе работу), скопируем его в созданную в корне диска папку C:\xmltoxsd. Далее в эту же папку мы копируем наш xmlfile.xml и все готово к началу.

Отрываем «Командную строку» (Пуск -> «Выполнить» -> «cmd»), переходим в наш каталог и вызываем с параметрами по умолчанию xsd.exe, передавая наш xmlfile.xml параметром:

И видим, что рядом появился файл xmlfile.xsd с содержимым.

Вот и все! Этих действий достаточно, для создания примитивного XSD файла, с которым можно работать. Но стоит понимать, что сам xsd.exe, как и любая другая утилита, ничего не знает про типы ваших полей (поэтому почти всегда тип полей будет string), а так же о всех вариациях атрибутов и параметров. То есть, если у какого-то тега нет атрибута в вашей XML, тогда его и не будет в описании. Поэтому XML должен быть наиболее полным и в случае, если элемент может содержать несколько дочерних полей, лучше добавить как минимум два, что бы xsd.exe понял, что это коллекция.

Синтаксис XSD не очень сложный, поэтому, если пишется достаточно серьезное описание, возможно придется поработать и напильником.

Шаг 2. Создание Class из XSD.

Для создания класса на языке C#, нам понадобится вновь использоваться xsd.exe но уже с другим параметром /classes, передав путь к нашему xmlfile.xsd.

После выполнения появится файл xmlfile.cs, содержимое которого приведено ниже в сжатом виде:

Шаг 3. Сериализация объектов в XML.

Получившиеся классы у нас лежат в файле xmlfile.cs. Далее его содержимое или сам файл добавляем в проект Visual Studio, после чего можно с ним работать. Я создам демонстративный объекты книг, после чего сохраню в файл в формате XML.

После запуска и открытия Output.xml можно увидеть, что мы сохранили так, как мы хотели (Нижний файл — «Созданный кодом«).

Как мы видим, форматирование было соблюдено, а данные были наполнены нами.

How to Generate XML from XSD in Eclipse

How to Generate XML from XSD in Eclipse

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

If you work on web services, you must have been using XSD. To test the web service, you need to generate XML from XSD file.

Generate XML from XSD

We can use Eclipse IDE to easily generate XML from the XSD file. Just follow the below steps to get XML from XSD.

  1. Select XSD File in project, right click for Menu and select Generate > XML File…
  2. Provide the XML file Name and XML File location in the popup window. Click on next button.
  3. Select the root element for which you want to generate the sample XML file, make sure to select checkboxes for “Create optional attributes” and “Create optional elements”. Below image shows how the window will look. generate xml from xsd5. Click on Finish button and it will generate the XML File for you with the default values. Now you can change the values according to your requirement.

XSD to XML Example

Here is the XSD for which I will be generating XML files. Employee.xsd

Since Employee.xsd has two root elements; empRequest and empResponse ; I can generate two XML files. Here are the XML files generated by Eclipse, the values are changed by me. EmployeeRequest.xml

I hope this quick tip will help you in generating XML from XSD easily.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *