Преобразовать xsd в excel

This answer is equally for you as well as @Alex, @Michael and @forty-two. I am illustrating it using Excel 2010, so if you’re on another version, I’ll leave it up to you to make the necessary adjustments.

First thing, make sure the developer tab shows (Click the File tab, Options).

Excel 2010 options for Developer tab

You now have to create an XML source from your XSD: click the Developer tab; in the XML group, toggle Source button to show the Xml Source task pane; then click the XML Maps button.

Excel showing key UI elements for creating an XML map

Click Add button at the prompt; point to the XSD file; then click OK to go back to the main screen.

Excel showing XSD loaded in an XML map

Then you can drag and drop your shipOrder to a cell in a worksheet, to anchor the generated mapped table.

Excel showing mapped XSD

Next, you may use Import to get your XML data into the spreadsheet, and Export to get it out. There are a couple of additional things to pay attention to; read this article on Microsoft’s site; pay particular attention to the issues with exporting XML data (error XML maps in my workbook are not exportable). This is because of the 1 to many cardinality between shiporder and item. You can try to handle it using mapped ranges — I’ll leave this all up to you. The best would be for you to read the online help for the XML developer section…

У меня есть файл XSD, и мне нужно преобразовать его в файл MS Excel.
XSD находится ниже.

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

<xs:element name="shiporder">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="orderperson" type="xs:string"/>
      <xs:element name="shipto">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="address" type="xs:string"/>
            <xs:element name="city" type="xs:string"/>
            <xs:element name="country" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="note" type="xs:string" minOccurs="0"/>
            <xs:element name="quantity" type="xs:positiveInteger"/>
            <xs:element name="price" type="xs:decimal"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="orderid" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

</xs:schema>

просьба помочь мне, я действительно не знаю как и с чего начать.

4 ответов


этот ответ одинаково для вас, а также @Alex, @Michael и @42. Я иллюстрирую его с помощью Excel 2010, поэтому, если вы находитесь в другой версии, я оставлю вам возможность внести необходимые изменения.

во-первых, убедитесь, что вкладка Разработчик показывает (нажмите вкладку Файл, Параметры).

Excel 2010 options for Developer tab

теперь вам нужно создать источник XML из вашего XSD: перейдите на вкладку Разработчик; в группе XML переключите кнопку Источник, чтобы показать задачу источник Xml панели; нажмите кнопку карты XML.

Excel showing key UI elements for creating an XML map

Нажмите кнопку Добавить в приглашении; укажите файл XSD; затем нажмите кнопку ОК, чтобы вернуться к главному экрану.

Excel showing XSD loaded in an XML map

затем вы можете перетащить свой shipOrder в ячейку на листе, чтобы закрепить сгенерированную сопоставленную таблицу.

Excel showing mapped XSD

далее, Вы можете использовать импорт, чтобы получить ваши данные XML в электронную таблицу, и экспорт, чтобы получить его. Есть несколько дополнительные вещи, на которые стоит обратить внимание; Читать эта статья на сайте Microsoft; обратите особое внимание на проблемы с экспортом XML-данных (ошибка XML-карты в моей книге не экспортируются). Это из-за 1 ко многим кардинальности между shiporder и item. Вы можете попытаться справиться с этим, используя сопоставленные диапазоны — я оставлю все это на вас. Лучше всего было бы вам прочитать онлайн-справку для раздела разработчика XML…


на MS Excel ->File ->Open. Выберите файл xsd.

вам будет предложено, как вы хотели бы открыть файл. Вы можете выбрать опцию «в качестве таблицы XML». Сохраните файл в формате Excel.

2

автор: Ashwath Padmashali


вы можете сохранить файл как XML-файл, а затем открыть его в Excel и открыть как «книгу только для чтения» при появлении запроса. Однако он не будет в хорошем формате, но, по крайней мере, все данные (вместе с XML-дорожки в виде столбцов) будет там.

вы можете редактировать данные по мере необходимости. Все остальное потребует некоторой обработки.


выберите весь текст XSD в текстовом редакторе, скопируйте его в буфер обмена, щелкните ячейку в электронной таблице Excel и выполните вставку. Ваши данные XSD теперь будут в вашей электронной таблице.

Это будет не очень полезный формат, но вы не сказали нам, как вы хотите, чтобы электронная таблица выглядела, и мне трудно представить себе формат, который б быть полезным.


Excel for Microsoft 365 Excel 2021 Excel 2019 Excel 2016 Excel 2013 Excel 2010 Excel 2007 More…Less

It is important to understand how XML Schema Definition (XSD) data types are handled when you import or export XML data, so that the data is appropriately converted according to your needs.

What do you want to do?

  • Learn how Excel handles XSD data types when you import XML data

  • Learn how Excel display formats map to XSD data types when you export XML data

Learn how Excel handles XSD data types when you import XML data

Important: If an XML schema file (.xsd) does not define a specific data type attribute for an element (such as xsd:decimal), then Excel formats the cell as text by default when the XML data is imported. Formatting as text ensures that the characters stored in the cell are exactly the same as the data that is stored in the XML file (.xml). For example, leading zero (0) values in an ID or credit card field are removed when they are formatted as a number, but not removed when they are formatted as text. However, data that is formatted as text does not evaluate. If you want the data to evaluate because it contains a formula, you must explicitly provide a numeric data type attribute, such as xsd:decimal or xsd:integer.

The following table lists the display formats that are applied when an item with a particular XSD data type is imported into an Excel worksheet. Data with an XSD format listed in the Unsupported formats column are imported as text values.

XSD data type

Excel display format

Unsupported formats

time

h:mm:ss

hh:mm:ssZ
Hh:mm:ss.f-f

dateTime

m/d/yyyy h:mm

yyyy-mm-ddThh:mm:ssZ
yyyy-mm-ddThh:mm:ss+/-hh:mm
yyyy-mm-ddThh:mm:ss.f-f
Years outside of the range 1900 to 9999

date

Date *3/14/2001

yyyy-mm-ddZ
yyyy-mm-dd+/-hh:mm
Years outside of the range 1900 to 9999

gYear

Number, no decimals

yyyy+/-hh:mm
Years outside of the range 1900 to 9999

gDay
gMonth

Number, no decimals

gYearMonth

Custom mmm-yy

yyyy-mm+/-hh:mm
Years outside of the range 1900 to 9999

gMonthDay

Custom d-mmm

anytype
anyURI
base64Binary
duration
ENTITIES
ENTITY
hexBinary
ID
IDREF
IDREFS
language
Name
NCName
NMTOKEN
NMTOKENS
normalizedString
NOTATION
QName
string
token

Text

boolean

Boolean

decimal
float
double

General

Leading and trailing zeros (0) are dropped.
Negative (-) and positive (+) signs are respected, although only negative signs are displayed.
Excel stores and calculates with 15 significant digits of precision.

byte
int
integer
long
negativeInteger
nonNegativeInteger
nonPositiveInteger
positiveInteger
short
unsignedByte
unsignedInt
unsignedLong
unsignedShort

General

Top of Page

Learn how Excel display formats map to XSD data types when you export XML data

When you export XML data, the exported data will match the data that is displayed in the worksheet, under the following circumstances:

  • The Excel display format is Text.

  • You have not changed the display format of the data.

If you change the display format of a cell that has numeric, date, or time data, then the underlying value of the cell is exported. For example, if you apply a Percentage display format to a cell that results in the display of 51.50%, the cell’s value will be exported as .515.

Top of Page

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

Этот ответ предназначен как для вас, так и для @Alex, @Michael и @forty-two. Я иллюстрирую это, используя Excel 2010, так что если вы используете другую версию, я оставляю за вами право внести необходимые коррективы.

Первым делом убедитесь, что отображается вкладка разработчика (щелкните вкладку Файл, Параметры).

Параметры Excel 2010 для вкладки "Разработчик"

Теперь вам нужно создать источник XML из вашего XSD: перейдите на вкладку Разработчик; в группе XML переключите кнопку Источник, чтобы отобразить панель задач Xml Source; затем нажмите кнопку XML Maps.

Excel показывает основные элементы пользовательского интерфейса для создания карты XML

Нажмите кнопку Добавить в подсказке; укажите на файл XSD; затем нажмите кнопку OK, чтобы вернуться на главный экран.

Excel показывает XSD, загруженный в XML-карту

Затем вы можете перетащить shipOrder в ячейку рабочего листа, чтобы привязать сгенерированную сопоставленную таблицу.

Excel показывает отображенный XSD

Далее вы можете использовать Импорт, чтобы ввести XML-данные в таблицу, и Экспорт, чтобы вывести их. Есть несколько дополнительных моментов, на которые следует обратить внимание; прочитайте эту статью на сайте Microsoft; обратите особое внимание на проблемы с экспортом XML-данных (ошибки XML-карт в моей рабочей книге не экспортируются). Это происходит из-за кардинальности 1 ко многим между shiporder и item. Вы можете попробовать справиться с этим с помощью отображаемых диапазонов — я оставляю это на ваше усмотрение. Лучше всего, если вы прочитаете онлайн-справку по разделу XML developer…

Файл с XSD расширением, скорее всего, являются файлом XML-схемы; текстовый формат файла, который определяет правила проверки для файла XML и объясняет форму XML.

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

Файлы XML могут ссылаться на файл XSD с атрибутом schemaLocation.

Программа вышивки крестиком Pattern Maker от HobbyWare также использует расширение XSD для своего формата.

Как открыть файл XSD

Поскольку XSD-файлы – это текстовые файлы, схожие по формату с XML-файлами, они следуют тем же правилам открытия/редактирования. Однако большинство вопросов, касающихся файлов XSD, связаны с тем, как их создавать.

SchemaViewer – это бесплатная программа, которая отображает XSD-файлы в правильном древовидном формате, что облегчает их чтение, чем в простом текстовом редакторе, таком как Блокнот.

XSD файлы можно также открыть с помощью Microsoft Visual Studio, XML Notepad, EditiX XML и XMLSpy. Oxygen XML Editor – один из немногих инструментов XSD, который работает на Linux, Mac и Windows.

Структура файла XSD в Microsoft Visual Studio

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

Вот пример того, как выглядит XSD-файл при открытии в текстовом редакторе:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:widgets="http://www.w3.org/ns/widgets">
<xs:group name="local">
<xs:sequence>
<xs:any namespace="##other" processContents="skip"/>
</xs:sequence>
</xs:group>
</xs:schema>

Если вы имеете дело с файлом XSD, используемым с Pattern Maker, вы, конечно, можете открыть его с помощью этого программного обеспечения. Однако для бесплатного открытия и печати файла шаблона HobbyWare предлагает программу Pattern Maker Viewer. Просто перетащите файл XSD в программу или используйте меню «Файл»«Открыть…». Этот просмотрщик также поддерживает аналогичный формат PAT.

Приложение Crossty для iOS и Android также может открывать XSD-файлы для вышивки крестом, но это не бесплатно.

Как конвертировать файл XSD

Самый простой способ конвертировать файл XSD в другой формат – использовать один из редакторов XSD, описанных выше.

Например, Visual Studio может сохранить открытый XSD-файл в XML, XSLT, XSL, DTD, TXT и других аналогичных форматах. JSON Schema Editor умеет конвертировать XSD в JSON.

Ещё одно преобразование, которое вам может понадобиться, – это XSD в PDF, чтобы вы могли открыть файл XSD в Adobe Acrobat Reader или каком-либо другом средстве просмотра PDF. Вероятно, нет особой причины конвертировать файл XSD в PDF, кроме как для того, чтобы код был виден на любом компьютере, который его открывает.

XML Schema Definition Tool может конвертировать XDR, XML и XSD файлы сериализуемого класса или набор данных, как # класса C.

Вы можете использовать Microsoft Excel, если вам нужно импортировать данные из файла XSD и поместить их в электронную таблицу Excel.

Вполне вероятно, что программа Pattern Maker, которую мы упомянули выше (не бесплатная программа просмотра), может быть использована для преобразования файла XSD для вышивания крестиком в новый формат файла.

Всё ещё не можете открыть файл?

Если ваш XSD-файл не открывается программами и инструментами, указанными выше, есть большая вероятность, что вы имеете дело не с XSD-файлом, а с файлом, имеющим аналогичное расширение.

Например, расширение XDS выглядит очень похоже на XSD, но вместо этого используется для файлов проекта DS Game Maker и файлов LcdStudio Design. Ни один из этих форматов файлов не связан с файлами или шаблонами XML.

Та же концепция применяется ко многим другим форматам файлов, таким как файлы XACT Sound Bank, которые используют расширение файла .XSB. Это звуковые файлы, которые не открываются с помощью какого-либо средства открывания XSD или конвертера файлов.

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

XML is a common file type for storing and transferring data. In this article, we are going to show you how to import XML files into Excel using two methods: First is a more «direct method» and the other is the Power Query approach.

Download Workbook

Let take a closer look at how you can import XML files into Excel.

Direct importing

This method works in Excel versions 2007 or newer. You need to make the Developer tab visible in the Ribbon to use this feature. The XML section in the Developer menu allows you to import, export and manage the XML files.

How to import XML files into Excel 01

Once the Developer tab is enabled, click the Import button in the XML section. Select your XML file in the File dialog, and click Import.

If you have not defined a schema beforehand, Excel will give you a warning and offer to create one for you.

How to import XML files into Excel 02

If you do not have a schema file listed with the XSD extension, click the OK button to let Excel do this. If, for some reason Excel fails at this step, try the other approach below.

Next, Excel will ask you where you want to import the workbook. You can select either a cell in an existing worksheet or create a new one.

How to import XML files into Excel 03

Clicking the OK button completes the importing process. Once the XML is imported, you can manage it from the same section, and update the data if the resource file is changed. Refresh (update) buttons can be found under both the Data or Table Design tabs of the Ribbon, as well as the right-click menu of the table.

How to import XML files into Excel 04

Importing XML files by using Power Query

Power Query is a powerful tool for importing and querying data, supported in Excel versions 2010 or newer. If you are using the 2010 or 2013 versions, you can download it as an add-in. Excel has implemented this feature into the base version starting with the 2016 version.

  1. If you’re using Excel with a Microsoft 365 subscription, follow Data > Get Data > From File > From XML.
    If you’re using Excel 2013 or earlier, follow Power Query > From File > From XML.
    How to import XML files into Excel 05
  2. Select your file under Import Data and click Import.
  3. Navigator displays a preview of your XML
  4. If you are satisfied with the preview, click the Load button to import the data.
    If you want to query data before adding into your spreadsheet, click Transform Data to open Power Query window.
    How to import XML files into Excel 06

You can access Power Query window any time by right-clicking the query in the Queries & Connections pane.

How to import XML files into Excel 07

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

1
branch

0
tags


Code

  • Use Git or checkout with SVN using the web URL.

  • Open with GitHub Desktop

  • Download ZIP

Latest commit

Files

Permalink

Failed to load latest commit information.

Type

Name

Latest commit message

Commit time

NIEM-XSD-to-Excel-Converter

Lastest version v2.3

as of 2/04/2016

Author: Thomas Rosales

Build using Windows Forms in C#. This tool is used to generate Excel Spreadsheets from NIEM (XSD) schemas. Compactible with extension, exchange, subset and codelist schemas.

It currently organized the schema contents into excel columns :

  • Class Name (Extension Class)
  • Element Name
  • Element Type
  • Documentation*
  • Source(opcional)*

#####*Schema Design:
-In order for the tool to capture the Documentation and Source correctly, an element should have a separate documentation tag for Documentation and another one for Source.

Important!: The source documentation must start with «Source:» (case sensitive)

Example:

  <xsd:element abstract="false" name="ProgramType" nillable="false" type="niem-xsd:string">
    <xsd:annotation>
      <xsd:documentation>Source: North Dakota</xsd:documentation>
      <xsd:documentation>Referral Type	Indicator of what system is sending this referral to STARS</xsd:documentation>
    </xsd:annotation>
  </xsd:element>

####Instructions:

  • Run exe (no installation required)
  • Press «Select NIEM XSD» button and choose NIEM schema file
  • Press «Convert To Excel» button.
  • Wait for operation to finish (should be quick)
  • Once done the spreadsheet will appear in the same directory as the schema selected.

####Disclamer:

  • This tool should be taken lightly. Once the spreadsheet is generated, it needs to be reviewed manually to make sure all elements were included. The tool does its best to capture everything inside the schema.

####Download Link:

  • https://github.com/Thwar/NIEM-XSD-to-Excel-Converter/blob/master/NIEMXML/App/NIEMXML.exe?raw=true

####Changes:

#####v2.3

  • Extension class now shows for simpleContent tags inside complexContent classes.

#####v2.2

  • Fixed no sequence errors
  • Modified file output process and message box
  • Tool now captures name and ref element attributes
  • Fixed cosmetic spreadsheet background color
  • Added schema definition
  • Source is now allowed without having description field.
  • Class now supports source definitions.

#####v2.0

  • Embeded DLLs for portability.
  • Faster processing. No longer requires Excel.
  • Better error catching.
  • Spreadsheet redesign
  • Added Source column

Понравилась статья? Поделить с друзьями:
  • Преобразовать xps в word онлайн
  • Преобразовать текст в список в excel
  • Преобразовать текст в пропись в excel
  • Преобразовать текст в одну строку в excel
  • Преобразовать текст в колонки в excel