Xml in windows application

Считывание XML-данных в набор данных Read XML data into a dataset

ADO.NET предоставляет простые методы для работы с XML-данными. ADO.NET provides simple methods for working with XML data. В этом пошаговом руководстве вы создадите приложение Windows, которое загружает XML-данные в набор данных. In this walkthrough, you create a Windows application that loads XML data into a dataset. Затем набор данных отображается в DataGridView элементе управления. The dataset is then displayed in a DataGridView control. Наконец, схема XML, основанная на содержимом XML-файла, отображается в текстовом поле. Finally, an XML schema based on the contents of the XML file is displayed in a text box.

Создание нового проекта Create a new project

Создайте новый проект Windows Forms приложения для C# или Visual Basic. Create a new Windows Forms App project for either C# or Visual Basic. Назовите проект реадингксмл. Name the project ReadingXML.

Создать XML-файл для чтения в наборе данных Generate the XML file to be read into the dataset

Поскольку в этом пошаговом руководстве рассматривается чтение XML-данных в наборе данных, предоставляется содержимое XML-файла. Because this walkthrough focuses on reading XML data into a dataset, the contents of an XML file is provided.

В меню Проект выберите команду Добавить новый элемент. On the Project menu, select Add New Item.

Выберите XML-файл, присвойте файлу имя authors.xml, а затем нажмите кнопку добавить. Select XML File, name the file authors.xml, and then select Add.

XML-файл загружается в конструктор и готов к редактированию. The XML file loads into the designer and is ready for edit.

Вставьте следующие XML-данные в редактор под XML-объявлением: Paste the following XML data into the editor below the XML declaration:

В меню файл выберите команду сохранить authors.xml. On the File menu, select Save authors.xml.

Создание пользовательского интерфейса Create the user interface

Пользовательский интерфейс для этого приложения состоит из следующих компонентов: The user interface for this application consists of the following:

DataGridViewЭлемент управления, отображающий содержимое XML-файла в виде данных. A DataGridView control that displays the contents of the XML file as data.

TextBoxЭлемент управления, отображающий XML-схему для XML-файла. A TextBox control that displays the XML schema for the XML file.

Два Button элемента управления. Two Button controls.

Одна кнопка считывает XML-файл в набор данных и отображает его в DataGridView элементе управления. One button reads the XML file into the dataset and displays it in the DataGridView control.

Вторая кнопка извлекает схему из набора данных, а затем StringWriter отображает ее в TextBox элементе управления. A second button extracts the schema from the dataset, and through a StringWriter displays it in the TextBox control.

Для добавления элементов управления в форму To add controls to the form

Откройте Form1 в режиме конструктора. Open Form1 in design view.

Перетащите следующие элементы управления из области элементов в форму: From the Toolbox, drag the following controls onto the form:

Один DataGridView элемент управления One DataGridView control

Один TextBox элемент управления One TextBox control

Два Button элемента управления Two Button controls

Задайте следующие свойства. Set the following properties:

Control Control Свойство. Property Параметр Setting
TextBox1 MultilineMultiline true
ScrollBarsScrollBars По вертикалиVertical
Button1 имя; Name ReadXmlButton
TextText Read XML
Button2 имя; Name ShowSchemaButton
TextText Show Schema

Создание набора данных, который получает XML-данные Create the dataset that receives the XML data

На этом шаге вы создадите новый набор данных с именем authors . In this step, you create a new dataset named authors . Дополнительные сведения о наборах данных см. в разделе Инструменты набора DataSet в Visual Studio. For more information about datasets, see Dataset tools in Visual Studio.

В Обозреватель решений выберите исходный файл для формы Form1, а затем нажмите кнопку конструктор представлений на панели инструментов Обозреватель решений . In Solution Explorer, select the source file for Form1, and then select the View Designer button on the Solution Explorer toolbar.

Перетащите набор данных из панели элементов на вкладку «данные»на форму Form1. From the Toolbox, Data tab, drag a DataSet onto Form1.

В диалоговом окне Добавление набора данных выберите параметр нетипизированный набор данных, а затем нажмите кнопку ОК. In the Add Dataset dialog box, select Untyped dataset, and then select OK.

DataSet1 добавляется в область компонентов. DataSet1 is added to the component tray.

В окне Свойства задайте имя и DataSetName свойства для AuthorsDataSet . In the Properties window, set the Name and DataSetName properties for AuthorsDataSet .

Создание обработчика событий для чтения XML-файла в наборе данных Create the event handler to read the XML file into the dataset

Кнопка » прочитать XML » считывает XML-файл в наборе данных. The Read XML button reads the XML file into the dataset. Затем в нем устанавливаются свойства DataGridView элемента управления, который привязывает его к набору данных. It then sets properties on the DataGridView control that bind it to the dataset.

В Обозреватель решений выберите Form1, а затем нажмите кнопку конструктор представлений на панели инструментов Обозреватель решений . In Solution Explorer, select Form1, and then select the View Designer button on the Solution Explorer toolbar.

Нажмите кнопку чтение XML . Select the Read XML button.

Редактор кода откроется в ReadXmlButton_Click обработчике событий. The Code Editor opens at the ReadXmlButton_Click event handler.

Введите следующий код в ReadXmlButton_Click обработчик событий: Type the following code into the ReadXmlButton_Click event handler:

В ReadXMLButton_Click коде обработчика событий измените filepath = запись на правильный путь. In the ReadXMLButton_Click event handler code, change the filepath = entry to the correct path.

Создание обработчика событий для вывода схемы в текстовое поле Create the event handler to display the schema in the textbox

Кнопка Показать схему создает StringWriter объект, который заполняется схемой и отображается в TextBox элементе управления. The Show Schema button creates a StringWriter object that’s filled with the schema and is displayed in the TextBoxcontrol.

В Обозреватель решений выберите Form1, а затем нажмите кнопку Конструктор представлений . In Solution Explorer, select Form1, and then select the View Designer button.

Нажмите кнопку отобразить схему . Select the Show Schema button.

Редактор кода откроется в ShowSchemaButton_Click обработчике событий. The Code Editor opens at the ShowSchemaButton_Click event handler.

Вставьте в обработчик события ShowSchemaButton_Click следующий код. Paste the following code into the ShowSchemaButton_Click event handler.

Тестирование формы Test the form

Теперь можно проверить форму, чтобы убедиться, что она ведет себя так, как ожидалось. You can now test the form to make sure it behaves as expected.

Нажмите клавишу F5 , чтобы запустить приложение. Select F5 to run the application.

Нажмите кнопку чтение XML . Select the Read XML button.

Элемент DataGridView отображает содержимое XML-файла. The DataGridView displays the contents of the XML file.

Нажмите кнопку отобразить схему . Select the Show Schema button.

В текстовом поле отображается схема XML для XML-файла. The text box displays the XML schema for the XML file.

Дальнейшие действия Next steps

В этом пошаговом руководстве рассматриваются основы чтения XML-файла в наборе данных, а также создание схемы на основе содержимого XML-файла. This walkthrough teaches you the basics of reading an XML file into a dataset, as well as creating a schema based on the contents of the XML file. Ниже приведены некоторые задачи, которые можно выполнить далее. Here are some tasks that you might do next:

Изменить данные в наборе данных и записать их обратно в формате XML. Edit the data in the dataset and write it back out as XML. Дополнительные сведения см. в разделе WriteXml. For more information, see WriteXml.

Измените данные в наборе данных и запишите их в базу данных. Edit the data in the dataset and write it out to a database.

Application Manifests

An application manifest is an XML file that describes and identifies the shared and private side-by-side assemblies that an application should bind to at run time. These should be the same assembly versions that were used to test the application. Application manifests may also describe metadata for files that are private to the application.

For a complete listing of the XML schema, see Manifest File Schema.

Application manifests have the following elements and attributes.

Element Attributes Required
assembly Yes
manifestVersion Yes
noInherit No
assemblyIdentity Yes
type Yes
name Yes
language No
processorArchitecture No
version Yes
publicKeyToken No
compatibility No
application No
supportedOS Id No
maxversiontested Id No
dependency No
dependentAssembly No
file No
name No
hashalg No
hash No
activeCodePage No
autoElevate No
disableTheming No
disableWindowFiltering No
dpiAware No
dpiAwareness No
gdiScaling No
highResolutionScrollingAware No
longPathAware No
printerDriverIsolation No
ultraHighResolutionScrollingAware No
msix No
heapType No

File Location

Application manifests should be included as a resource in the application’s EXE file or DLL.

File Name Syntax

The name of an application manifest file is the name of the application’s executable followed by .manifest.

For example, an application manifest that refers to example.exe or example.dll would use the following file name syntax. You can omit the field if resource ID is 1.

example.exe. .manifest

example.dll. .manifest

Elements

Names of elements and attributes are case-sensitive. The values of elements and attributes are case-insensitive, except for the value of the type attribute.

assembly

A container element. Its first subelement must be a noInherit or assemblyIdentity element. Required.

The assembly element must be in the namespace «urn:schemas-microsoft-com:asm.v1». Child elements of the assembly must also be in this namespace, by inheritance or by tagging.

The assembly element has the following attributes.

Attribute Description
manifestVersion The manifestVersion attribute must be set to 1.0.

noInherit

Include this element in an application manifest to set the activation contexts generated from the manifest with the «no inherit» flag. When this flag is not set in an activation context, and the activation context is active, it is inherited by new threads in the same process, windows, window procedures, and Asynchronous Procedure Calls. Setting this flag prevents the new object from inheriting the active context.

The noInherit element is optional and typically omitted. Most assemblies do not work correctly using a no-inherit activation context because the assembly must be explicitly designed to manage the propagation of their own activation context. The use of the noInherit element requires that any dependent assemblies referenced by the application manifest have a noInherit element in their assembly manifest.

If noInherit is used in a manifest, it must be the first subelement of the assembly element. The assemblyIdentity element should come immediately after the noInherit element. If noInherit is not used, assemblyIdentity must be the first subelement of the assembly element. The noInherit element has no child elements. It is not a valid element in assembly manifests.

assemblyIdentity

As the first subelement of an assembly element, assemblyIdentity describes and uniquely identifies the application owning this application manifest. As the first subelement of a dependentAssembly element, assemblyIdentity describes a side-by-side assembly required by the application. Note that every assembly referenced in the application manifest requires an assemblyIdentity that exactly matches the assemblyIdentity in the referenced assembly’s own assembly manifest.

The assemblyIdentity element has the following attributes. It has no subelements.

Attribute Description
type Specifies the application or assembly type. The value must be Win32 and all in lower case. Required.
name Uniquely names the application or assembly. Use the following format for the name: Organization.Division.Name. For example Microsoft.Windows.mysampleApp. Required.
language Identifies the language of the application or assembly. Optional. If the application or assembly is language-specific, specify the DHTML language code. In the assemblyIdentity of an application intended for worldwide use (language neutral) omit the language attribute.
In an assemblyIdentity of an assembly intended for worldwide use (language neutral) set the value of language to «*».
processorArchitecture Specifies the processor. Valid values include x86 , amd64 , arm and arm64 . Optional.
version Specifies the application or assembly version. Use the four-part version format: mmmmm.nnnnn.ooooo.ppppp. Each of the parts separated by periods can be 0-65535 inclusive. For more information, see Assembly Versions. Required.
publicKeyToken A 16-character hexadecimal string representing the last 8 bytes of the SHA-1 hash of the public key under which the application or assembly is signed. The public key used to sign the catalog must be 2048 bits or greater. Required for all shared side-by-side assemblies.

compatibility

Contains at least one application. It has no attributes. Optional. Application manifests without a compatibility element default to Windows Vista compatibility on Windows 7.

application

Contains at least one supportedOS element. Starting in Windows 10, version 1903, it can also contain one optional maxversiontested element. It has no attributes. Optional.

supportedOS

The supportedOS element has the following attribute. It has no subelements.

Attribute Description
Id Set the Id attribute to to run the application using Vista functionality. This can enable an application designed for Windows Vista to run on a later operating system.
Set the Id attribute to to run the application using Windows 7 functionality.
Applications that support Windows Vista, Windows 7, and Windows 8 functionality do not require separate manifests. In this case, add the GUIDs for all the Windows operating systems.
For info about the Id attribute behavior in Windows, see the Windows 8 and Windows Server 2012 Compatibility Cookbook.
The following GUIDs correspond with the indicated operating systems:
-> Windows 10, Windows Server 2016 and Windows Server 2019
-> Windows 8.1 and Windows Server 2012 R2
-> Windows 8 and Windows Server 2012
-> Windows 7 and Windows Server 2008 R2
-> Windows Vista and Windows Server 2008
You can test this on Windows 7 or Windows 8.x by running Resource Monitor (resmon), going to the CPU tab, right-clicking on the column labels, «Select Column. «, and check «Operating System Context». On Windows 8.x, you can also find this column available in the Task Manager (taskmgr). The content of the column shows the highest value found or «Windows Vista» as the default.

maxversiontested

The maxversiontested element specifies the maximum version of Windows that the application was tested against. This is intended to be used by desktop applications that use XAML Islands and that are not deployed in an MSIX package. This element is supported in Windows 10, version 1903, and later versions.

The maxversiontested element has the following attribute. It has no subelements.

Attribute Description
Id Set the Id attribute to a 4-part version string that specifies the maximum version of Windows that the application was tested against. For example, «10.0.18226.0».

dependency

Contains at least one dependentAssembly. It has no attributes. Optional.

dependentAssembly

The first subelement of dependentAssembly must be an assemblyIdentity element that describes a side-by-side assembly required by the application. Every dependentAssembly must be inside exactly one dependency. It has no attributes.

Specifies files that are private to the application. Optional.

The file element has the attributes shown in the following table.

Attribute Description
name Name of the file. For example, Comctl32.dll.
hashalg Algorithm used to create a hash of the file. This value should be SHA1.
hash A hash of the file referred to by name. A hexadecimal string of length depending on the hash algorithm.

activeCodePage

Force a process to use UTF-8 as the process code page.

activeCodePage was added in Windows Version 1903 (May 2019 Update). You can declare this property and target/run on earlier Windows builds, but you must handle legacy code page detection and conversion as usual. See Use the UTF-8 code page for details.

This element has no attributes. UTF-8 is only valid value for activeCodePage element.

autoElevate

Specifies whether auto elevate is enabled. TRUE indicates that it is enabled. It has no attributes.

disableTheming

Specifies whether giving UI elements a theme is disabled. TRUE indicates disabled. It has no attributes.

disableWindowFiltering

Specifies whether to disable window filtering. TRUE disables window filtering so you can enumerate immersive windows from the desktop. disableWindowFiltering was added in Windows 8 and has no attributes.

dpiAware

Specifies whether the current process is dots per inch (dpi) aware.

Windows 10, version 1607: The dpiAware element is ignored if the dpiAwareness element is present. You can include both elements in a manifest if you want to specify a different behavior for Windows 10, version 1607 than for an earlier version of the operating system.

The following table describes the behavior that results based upon the presence of the dpiAware element and the text that it contains. The text within the element is not case-sensitive.

State of the dpiAware element Description
Absent The current process is dpi unaware by default. You can programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
Contains «true» The current process is system dpi aware.
Contains «false» Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is dpi unaware, and you cannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
Contains «true/pm» Windows Vista, Windows 7 and Windows 8: The current process is system dpi aware.
Windows 8.1 and Windows 10: The current process is per-monitor dpi aware.
Contains «per monitor» Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is per-monitor dpi aware.
Contains any other string Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is dpi unaware, and you cannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.

For more information about dpi awareness settings, see Comparison of DPI Awareness Levels.

dpiAware has no attributes.

dpiAwareness

Specifies whether the current process is dots per inch (dpi) aware.

The minimum version of the operating system that supports the dpiAwareness element is Windows 10, version 1607. For versions that support the dpiAwareness element, the dpiAwareness overrides the dpiAware element. You can include both elements in a manifest if you want to specify a different behavior for Windows 10, version 1607 than for an earlier version of the operating system.

The dpiAwareness element can contain a single item or a list of comma-separated items. In the latter case, the first (leftmost) item in the list recognized by the operating system is used. In this way, you can specify different behaviors supported in future Windows operating system versions.

The following table describes the behavior that results based upon the presence of the dpiAwareness element and the text that it contains in its leftmost recognized item. The text within the element is not case-sensitive.

dpiAwareness element status: Description
Element is absent The dpiAware element specifies whether the process is dpi aware.
Contains no recognized items The current process is dpi unaware by default. You can programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
First recognized item is «system» The current process is system dpi aware.
First recognized item is «permonitor» The current process is per-monitor dpi aware.
First recognized item is «permonitorv2» The current process uses the per-monitor-v2 dpi awareness context. This item will only be recognized on Windows 10 version 1703 or later.
First recognized item is «unaware» The current process is dpi unaware. Youcannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.

For more information about dpi awareness settings supported by this element, see DPI_AWARENESS and DPI_AWARENESS_CONTEXT.

dpiAwareness has no attributes.

gdiScaling

Specifies whether GDI scaling is enabled. The minimum version of the operating system that supports the gdiScaling element is Windows 10 version 1703.

The GDI (graphics device interface) framework can apply DPI scaling to primitives and text on a per-monitor basis without updates to the application itself. This can be useful for GDI applications no longer being actively updated.

Non-vector graphics (such as bitmaps, icons, or toolbars) cannot be scaled by this element. In addition, graphics and text appearing within bitmaps dynamically constructed by applications also cannot be scaled by this element.

TRUE indicates that this element is enabled. It has no attributes.

highResolutionScrollingAware

Specifies whether high-resolution-scrolling aware is enabled. TRUE indicates that it is enabled. It has no attributes.

longPathAware

Enables long paths that exceed MAX_PATH in length. This element is supported in Windows 10, version 1607, and later. For more information, see this article.

printerDriverIsolation

Specifies whether printer driver isolation is enabled. TRUE indicates that it is enabled. It has no attributes. Printer driver isolation improves the reliability of the Windows print service by enabling printer drivers to run in processes that are separate from the process in which the print spooler runs. Support for printer driver isolation started in Windows 7 and Windows Server 2008 R2. An app can declare printer driver isolation in its app manifest to isolate itself from the printer driver and improve its reliability. That is, the app won’t crash if the printer driver has an error.

ultraHighResolutionScrollingAware

Specifies whether ultra-high-resolution-scrolling aware is enabled. TRUE indicates that it is enabled. It has no attributes.

Specifies the identity info of a sparse MSIX package for the current application. This element is supported in Windows 10, version 2004, and later versions.

The msix element must be in the namespace urn:schemas-microsoft-com:msix.v1 . It has the attributes shown in the following table.

Attribute Description
publisher Describes the publisher information. This value must match the Publisher attribute in the Identity element in your sparse package manifest.
packageName Describes the contents of the package. This value must match the Name attribute in the Identity element in your sparse package manifest.
applicationId The unique identifier of the application. This value must match the Id attribute in the Application element in your sparse package manifest.

heapType

Overrides the default heap implementation for the Win32 heap APIs to use.

  • The value SegmentHeap indicates that segment heap will be used. Segment heap is a modern heap implementation that will generally reduce your overall memory usage. This element is supported in Windows 10, version 2004 (build 19041) and later.
  • All other values are ignored.
Читайте также:  Ccleaner для ноутбука windows
Оцените статью