Импорт содержимого XML в классы - C#
Формулировка задачи:
прошу помощи, перепробовал видимо уже все кроме того что нужно.
Задача состоит в том, чтобы взять xml файл
и импортировать его в классы с#
ВОТ ЧТО ЕСТЬ НА ДАННЫЙ МОМЕНТ
Класс ТОВАР в который хочу впихнуть этот файл
ну и main
string name = nodeList.Item(i).Value - перебрал уже все что можно. но пока не особо(((
Подскажите где ошибка???
<?xml version="1.0" encoding="utf-8"?>
<Shop name="Kvazetka">
<Item type="clothes">
<name>Рубашка мужская</name>
<info size="48" matherial="cotton"/>
</Item>
<Item type="clothes">
<name>Кофта вязаная, женская</name>
<info size="36" matherial="lycra"/>
</Item>
<Item type="shoes">
<name>Кроссовки беговые</name>
<info size="37" matherial="polyester"/>
</Item>
<Item type="accessories">
<name>Часы наручные, мужские</name>
<info size="15" matherial="metal"/>
</Item>
<Item type="shoes">
<name>Туфли мужские</name>
<info size="42" matherial="leather"/>
</Item>
<Item type="clothes">
<name>Джинсы женские</name>
<info size="40" matherial="cotton"/>
</Item>
<Item type="clothes">
<name>Джинсы мужские</name>
<info size="46" matherial="cotton"/>
</Item>
<Item type="shoes">
<name>Туфли осенние</name>
<info size="43" matherial="leather"/>
</Item>
<Item type="shoes">
<name>Сапоги зимние</name>
<info size="36" matherial="leather"/>
</Item>
<Item type="accessories">
<name>Бусы, бижутерия</name>
<info size="25" matherial="plastic"/>
</Item>
<Item type="accessories">
<name>Кулон, серебро</name>
<info size="5" matherial="silver"/>
</Item>
</Shop>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Tovar
{
string name;
int info_size;
string info_material;
public Tovar()
{
name = "нет товара";
info_size = 0;
info_material = "волшебный";
}
public Tovar(string name, int info_size, string info_material)
{
this.name = name;
this.info_size = info_size;
this.info_material = info_material;
}
public string GetName()
{
return name;
}
public int GetInfoSize()
{
return info_size;
}
public string GetInfoMaterial()
{
return info_material;
}
public override string ToString()
{
return name + " " + info_size + " " + info_material + " ";
}
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConsoleApplication2
{
class Program
{
public static void show_xml(XmlNode node)
{
//Параметр node
//Для начала выведем имя этого узла
Console.WriteLine("{0} {1}\t\t{2}", node.Name, node.NodeType, node.Value);
//вытаскиваем значения атрибутов
if (node.Attributes != null)
{
foreach (XmlAttribute att in node.Attributes)
Console.WriteLine("------------ {0} {1}", att.Name, att.Value);
}
//если у узла есть дочерние элименты, запускаем цикл для этих элементов
if (node.HasChildNodes == true)
{
//берем коллекцию всех дочерних узлов
XmlNodeList Child = node.ChildNodes;
foreach (XmlNode item in Child)
{
show_xml(item);
}
}
}
static void Main(string[] args)
{
List<Tovar> tovar = new List<Tovar>();
XmlDocument doc = new XmlDocument();
try
{
Console.WriteLine("Все работает");
doc.Load("Products.xml");
//выводим имя корневого узла
Console.WriteLine(doc.DocumentElement.Name);
show_xml(doc.DocumentElement);
Console.WriteLine("____________________________________________________________________________");
XmlElement root = doc.DocumentElement;
XmlNodeList nodeList = root.GetElementsByTagName("Item");
for(int i=0; i<nodeList.Count; i++)
{
//-----как это реализовать ума не приложу
string name = nodeList.Item(i).Value;
int info_size=nodeList.Item(i).Value; //здесь тоже косяк, нужно привести к int
string info_material = nodeList.Item(i).Value;
Console.WriteLine(nodeList.Item(i).InnerXml);
tovar.Add(new Tovar(name, info_size, info_material));
tovar[i].GetName();
tovar[i].GetInfoSize();
tovar[i].GetType();
}
Console.WriteLine("****************************************************************************");
for (int i=0; i < tovar.Count; i++) {
Console.WriteLine(tovar[i].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("открыть документ не удалось");
Console.WriteLine(ex.ToString());
}
}
}
}Решение задачи: «Импорт содержимого XML в классы»
textual
Листинг программы
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.18408
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// Этот исходный код был создан с помощью xsd, версия=4.0.30319.33440.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Shop {
private ShopItem[] itemField;
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Item")]
public ShopItem[] Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class ShopItem {
private string nameField;
private ShopItemInfo infoField;
private string typeField;
/// <remarks/>
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public ShopItemInfo info {
get {
return this.infoField;
}
set {
this.infoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class ShopItemInfo {
private byte sizeField;
private string matherialField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte size {
get {
return this.sizeField;
}
set {
this.sizeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string matherial {
get {
return this.matherialField;
}
set {
this.matherialField = value;
}
}
}