C как из xmldocument получить класс
Для работы с XML в C# можно использовать несколько подходов. В первых версиях фреймворка основной функционал работы с XML предоставляло пространство имен System.Xml . В нем определен ряд классов, которые позволяют манипулировать xml-документом:
XmlNode : представляет узел xml. В качестве узла может использоваться весь документ, так и отдельный элемент
XmlDocument : представляет весь xml-документ
XmlElement : представляет отдельный элемент. Наследуется от класса XmlNode
XmlAttribute : представляет атрибут элемента
XmlText : представляет значение элемента в виде текста, то есть тот текст, который находится в элементе между его открывающим и закрывающим тегами
XmlComment : представляет комментарий в xml
XmlNodeList : используется для работы со списком узлов
Ключевым классом, который позволяет манипулировать содержимым xml, является XmlNode , поэтому рассмотрим некоторые его основные методы и свойства:
Свойство Attributes возвращает объект XmlAttributeCollection , который представляет коллекцию атрибутов
Свойство ChildNodes возвращает коллекцию дочерних узлов для данного узла
Свойство HasChildNodes возвращает true , если текущий узел имеет дочерние узлы
Свойство FirstChild возвращает первый дочерний узел
Свойство LastChild возвращает последний дочерний узел
Свойство InnerText возвращает текстовое значение узла
Свойство InnerXml возвращает всю внутреннюю разметку xml узла
Свойство Name возвращает название узла. Например, <user> — значение свойства Name равно «user»
Свойство ParentNode возвращает родительский узел у текущего узла
Применим эти классы и их функционал. И вначале для работы с xml создадим новый файл. Назовем его people.xml и определим в нем следующее содержание:
Теперь пройдемся по этому документу и выведем его данные на консоль:
В итоге я получу следующий вывод на консоли:
Чтобы начать работу с документом xml, нам надо создать объект XmlDocument и затем загрузить в него xml-файл: xDoc.Load(«people.xml»);
При разборе xml для начала мы получаем корневой элемент документа с помощью свойства xDoc.DocumentElement . Далее уже происходит собственно разбор узлов документа.
В цикле foreach(XmlNode xnode in xRoot) пробегаемся по всем дочерним узлам корневого элемента. Так как дочерние узлы представляют элементы <person> , то мы можем получить их атрибуты: XmlNode attr = xnode.Attributes.GetNamedItem(«name»); и вложенные элементы: foreach(XmlNode childnode in xnode.ChildNodes)
Чтобы определить, что за узел перед нами, мы можем сравнить его название: if(childnode.Name==»company»)
Подобным образом мы можем создать объекты классов и структур по данным из xml:
В данном случае определен класс Person с тремя свойствами. При переборе узлов файла xml значения элементов и их атрибутов передается объекту класса Person.
C как из xmldocument получить класс
We can create a class from given XML in Microsoft Visual Studio 2019. That means, we can copy the XML and can paste it as C# class in VS 2019.
Let’s consider following XML and copy it (Ctrl + C).
Open Microsoft Visual Studio 2019 => Create new console application. Add new C# class to the solution and name it as Employees.cs.
Copy the above XML (Ctrl + C) and on Visual Studio, go to Edit => Paste Special => select “Paste XML As Classes” as shown below.
It creates the Employees class, as shown below.
Even we can create a class from JSON response also by selecting “Paste JSON As Classes”.
Convert XML and JSON to C# Classes
Today I found a cool Visual Studio functionality: you can paste an XML or JSON source as Classes, in fact creating all the object model to serialize and deserialize object with the xml format, all this without using xsd.exe tool.
Here’s the very simple steps regarding an XML but it’s the same for JSON:
1 – The most difficult step….. copy the xml source in the clipboard, something like CTRL+A and CTRL+C

Is ridiculous to add a screenshot, but I’ve got it, so why not!
2 – Create a new empy class file… no more screenshot please! ok here we go
3 – Go to Edit -> Paste Special -> Paste XML As Classes, to paste the generated classes based on the source xml
Generate C# class from XML
If you are working on .NET 4.5 project in VS 2012 (or newer), you can just Special Paste your XML file as classes.
- Copy your XML file’s content to clipboard
- In editor, select place where you want your classes to be pasted
- From the menu, select EDIT > Paste Special > Paste XML As Classes
Notes
If you generate classes for multi-dimensional array, there is a bug in XSD.exe generator, but there are workarounds.
![]()
At first I thought the Paste Special was the holy grail! But then I tried it and my hair turned white just like the Indiana Jones movie.
But now I use http://xmltocsharp.azurewebsites.net/ and now I’m as young as ever.
Here’s a segment of what it generated:
![]()
I had the same problem as you so I decided to write my own program.
The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.
It is in no way elegant but it did the job for me. You can get it here: SimpleXmlToCode
Please make suggestions if you like it.
![]()
![]()
You should consider svcutil (svcutil question)
Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.
Note that various 3rd party tools also exist for this.
You can use xsd as suggested by Darin.
In addition to that it is recommended to edit the test.xsd-file to create a more reasonable schema.
type=»xs:string» can be changed to type=»xs:int» for integer values
minOccurs=»0″ can be changed to minOccurs=»1″ where the field is required
maxOccurs=»unbounded» can be changed to maxOccurs=»1″ where only one item is allowed
You can create more advanced xsd-s if you want to validate your data further, but this will at least give you reasonable data types in the generated c#.
Use below syntax to create schema class from XSD file.
Found this site a bit ago. It converts XML and JSON to C# and Java classes. Has several options to tweak as you need. I use it pretty often. https://json2csharp.com/xml-to-csharp
To convert XML into a C# Class:
- Navigate to the Microsoft Visual Studio Marketplace: — https://marketplace.visualstudio.com
- In the search bar enter text: — xml to class code tool
- Download, install, and use the app
Note: in the fullness of time, this app may be replaced, but chances are, there’ll be another tool that does the same thing.