Serializacja XML i odczyt zagłębień pozycji kolejnych kategorii jak to zrobić?

0

Witam
Mam problem z wykonaniem Serializacji danych XML. Posiadam plik XML który zawiera "drzewo" główne i podkategorie w których są pozycje z kolejnymi w nich zagnieżdżonymi pozycjami danych i teraz chciałbym móc je odczytać do zmiennych w programie w którym utworzyłem plik Xml.cs w którym stworzyłem odpowiednie klasy i pola do pobrania tych danych w celu przypisania odczytanyh danych z pliku XML do tych zmiennych oraz klas. Pytanie i prośba o pomoc czy poprawnie to zrobiłem bo przy uruchomieniu programu dostaje błąd o długiej treści i nie wiem dlaczego i gdzie zrobiłem coś źle?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Segregacja
{
    [XmlRoot("Document")]
    public class Document
    {
        [XmlElement(ElementName = "PositionTopLeft")]
        public int PositionTopLeft;
        [XmlElement(ElementName = "Width")]
        public int Width;
        [XmlElement(ElementName = "Height")]
        public int Height;
        [XmlArray("Title")]
        public Title[] Titles;
        [XmlArray("BootleType")]
        public BootleType[] BootleTypes;
        [XmlArray("Shift")]
        public Shift[] Shifts;
        [XmlArray("DateTime")]
        public DatesTime[] dateTimes;
    }
    
    public class DatesTime
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
    }

    public class Shift
    {
        [XmlElement(ElementName = "Title")]
        public String Title;
        [XmlElement(ElementName = "TitleNoNumber")]
        public String TitleNoNumber;
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlArray("Number")]
        public Number[] Numbers;
        [XmlElement(ElementName = "DefaultOption")]
        public int DefaultOption;
        [XmlElement(ElementName = "DefaultChackedYesNoShift")]
        public int DefaultCheckedYesNoShift;
    }

    public class Number
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String[] Param = new String[50];
    }
    public class BootleType
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlArray("Item")]
        public Item[] Items;
    }

    public class Item
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String[] Param = new String[50];
    }

    public class Title
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlElement(ElementName = "Text")]
        public String Text;
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<Document>
	<PositionTopLeft>0</PositionTopLeft>
	<Width>825</Width>
	<Height>630</Height>
	<Title>
		<PosY>0</PosY>
		<Text>TYTUŁ</Text>
	</Title>
	<BootleType>
		<PosY>150</PosY>
		<Item>
			<Param>PIERWSZY</Param>
			<Param>DRUGI</Param>
			<Param>TRZECI</Param>
			<Param>CZWARTY</Param>
			<Param>PIĄTY</Param>
			<Param>SZÓSTY</Param>
			<Param>SIÓDMY</Param>
			<Param>ÓSMY</Param>
			<Param>DZIEWIĄTY</Param>
		</Item>
	</BootleType>
	<Shift>
		<Title>ZMIANA</Title>
		<TitleNoNumber>ZMIANA ....</TitleNoNumber>
		<PosY>330</PosY>
		<Number>
			<Param>I</Param>
			<Param>II</Param>
			<Param>III</Param>
		</Number>
		<DefaultOption>0</DefaultOption>
		<DefaultCheckedYesNoShift>0</DefaultCheckedYesNoShift>
	</Shift>
	<DatesTime>
		<PosY>530</PosY>
	</DatesTime>
</Document>
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Document));
xmlSerializer.UnknownNode += new XmlNodeEventHandler(XmlSerializer_UnknownNode);
xmlSerializer.UnknownAttribute += new XmlAttributeEventHandler(XmlSerializer_UnknownAttribute);
StreamReader reader = new StreamReader(@XmlPath);
Document document = (Document)xmlSerializer.Deserialize(reader);

protected void XmlSerializer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            MessageBox.Show("Unknown Node:" + e.Name + "\t" + e.Text,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }

        protected void XmlSerializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            System.Xml.XmlAttribute attr = e.Attr;
            MessageBox.Show("Unknown attribute " +
            attr.Name + "='" + attr.Value + "'","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }

screenshot-20191118124945.png

Czemu nie wczytuje mi się to poprawnie gdzie mam błąd?

0

Mnie się wydaje, że struktura Document nie odpowiada xmlowi. Np to

[XmlArray("Shift")]
 public Shift[] Shifts;

W xml nie masz "tablicy"

0
szydlak napisał(a):

Mnie się wydaje, że struktura Document nie odpowiada xmlowi. Np to

[XmlArray("Shift")]
 public Shift[] Shifts;

W xml nie masz "tablicy"

A jak wyjaśnisz ten przykład z MSDN?

[XmlRoot("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
    public Address ShipTo;
    public string OrderDate;
    // The XmlArray attribute changes the XML element name
    // from the default of "OrderedItems" to "Items".
    [XmlArray("Items")]
    public OrderedItem[] OrderedItems;
    public decimal SubTotal;
    public decimal ShipCost;
    public decimal TotalCost;
}

Wzorowałem się na tym ale u mnie nie działa
https://docs.microsoft.com/pl-pl/dotnet/standard/serialization/examples-of-xml-serialization#serializing-an-xmlelement-and-xmlnode
Pisze wyraźnie że XmlArray zmienia nazwe zmiennej na nazwe która ma być zapisywana jako element domyślnie w XML-u.

0

XML z MS

<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ItemsOrders>
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        </Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        </Item>
    </ItemsOrders>
</PurchaseOrder>

A twój.

<Document>
    <PositionTopLeft>0</PositionTopLeft>
    <Width>825</Width>
    <Height>630</Height>
    <Title>
        <PosY>0</PosY>
        <Text>TYTUŁ</Text>
    </Title>
    <BootleType>
        <PosY>150</PosY>
        <Item>
            <Param>PIERWSZY</Param>
            <Param>DRUGI</Param>
            <Param>TRZECI</Param>
            <Param>CZWARTY</Param>
            <Param>PIĄTY</Param>
            <Param>SZÓSTY</Param>
            <Param>SIÓDMY</Param>
            <Param>ÓSMY</Param>
            <Param>DZIEWIĄTY</Param>
        </Item>
    </BootleType>
    <Shift>
        <Title>ZMIANA</Title>
        <TitleNoNumber>ZMIANA ....</TitleNoNumber>
        <PosY>330</PosY>
        <Number>
            <Param>I</Param>
            <Param>II</Param>
            <Param>III</Param>
        </Number>
        <DefaultOption>0</DefaultOption>
        <DefaultCheckedYesNoShift>0</DefaultCheckedYesNoShift>
    </Shift>
    <DatesTime>
        <PosY>530</PosY>
    </DatesTime>
</Document>

Nie widzisz różnicy w tablicy?

0

No wiem że nie są takie same bo robie inny projekt niż oni ale jak wiadomo skądś trzeba czerpać wiedze prawda? No i utknąłem przy odczytywaniu mojego XML i nie wiem co jest nie tak i jak powinno być?

0

No to próbuje Cię naprowadzić. Chodzi o to, że w XML jeśli masz "tablice" to każdy jej element powinien być zagnieżdżony

<ItemsOrders>
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        </Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        </Item>
</ItemsOrders>

Czyli jeśli twój xml jest prawidłowy to klasa Document

zamiast

[XmlArray("Shift")]
public Shift[] Shifts;

powinna mieć

[XmlElement("Shift")]
public Shift Shift;

Inne elementy też przeanalizuj sobie

0
szydlak napisał(a):

No to próbuje Cię naprowadzić. Chodzi o to, że w XML jeśli masz "tablice" to każdy jej element powinien być zagnieżdżony

<ItemsOrders>
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        </Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        </Item>
</ItemsOrders>

Czyli jeśli twój xml jest prawidłowy to klasa Document

zamiast

[XmlArray("Shift")]
public Shift[] Shifts;

powinna mieć

[XmlElement("Shift")]
public Shift Shift;

Inne elementy też przeanalizuj sobie

Ok zrobiłem zmiane tak jak Napisałes ale błąd dalej występuje w <Param> ponieważ komunikat błędu jasno mówi o "XmlChoiceIdentifierAttribute" aby dodać coś do Param tylko nie bardzo wiem o co może chodzić?
https://docs.microsoft.com/pl-pl/dotnet/api/system.xml.serialization.xmlchoiceidentifierattribute?view=netframework-4.8

Mam tak zadeklarowane pole Param

public class Item
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String[] Param = new String[50];
    }

Czy może chodzić o to że Param w XML-u nie jest tablicowy i trzeba zmienić na zwykłe pole typu String np. tak:

public class Item
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String Param;
    }

Jak powinno być? Bo rozumiem że wielokrotne użycie w XML-u <Param> jest prawidłowe czy trzeba to jakoś np. ponumerować lub czy nazwa nie może się powtarzać?

0

A inne elementy analizowałeś? Bo inne klasy np BootleType też się nie zgadzają

0
szydlak napisał(a):

A inne elementy analizowałeś? Bo inne klasy np BootleType też się nie zgadzają

Jakbyś mógł mi pomóc byłbym wdzięczny. Sprawdź mój post wyżej bo edytowałem go dodając nowe wpisy.

Obecnie wygląda tak:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Segregacja
{
    [XmlRoot("Document")]
    public class Document
    {
        [XmlElement(ElementName = "PositionTopLeft")]
        public int PositionTopLeft;
        [XmlElement(ElementName = "Width")]
        public int Width;
        [XmlElement(ElementName = "Height")]
        public int Height;
        [XmlElement("Title")]
        public Title Titles;
        [XmlElement("BootleType")]
        public BootleType BootleTypes;
        [XmlElement("Shift")]
        public Shift Shifts;
        [XmlElement("DateTime")]
        public DatesTime dateTimes;
    }
    
    public class DatesTime
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
    }

    public class Shift
    {
        [XmlElement(ElementName = "Title")]
        public String Title;
        [XmlElement(ElementName = "TitleNoNumber")]
        public String TitleNoNumber;
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlElement("Number")]
        public Number Numbers;
        [XmlElement(ElementName = "DefaultOption")]
        public int DefaultOption;
        [XmlElement(ElementName = "DefaultCheckedYesNoShift")]
        public int DefaultCheckedYesNoShift;
    }

    public class Number
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String[] Param = new String[50];
    }
    public class BootleType
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlElement("Item")]
        public Item Items;
    }

    public class Item
    {
        [XmlElement(ElementName = "Param")]
        [XmlElement(IsNullable = false)]
        public String[] Param = new String[50];
    }

    public class Title
    {
        [XmlElement(ElementName = "PosY")]
        public int PosY;
        [XmlElement(ElementName = "Text")]
        public String Text;
    }
}

0

Troche zmian i nadal jak był Error tak jest :/ ktoś wie co jest nie tak?
Podaje aktualny kod poniżej:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Segregacja
{
    [XmlRoot("Document")]
    public class Document
    {
        [XmlElement("PositionTopLeft")]
        public int PositionTopLeft { get; set; }
        [XmlElement("Width")]
        public int Width { get; set; }
        [XmlElement("Height")]
        public int Height { get; set; }
        [XmlElement("Title")]
        public Title Titles;
        [XmlElement("BootleType")]
        public BootleType BootleTypes;
        [XmlElement("Shift")]
        public Shift Shifts;
        [XmlElement("DateTime")]
        public DatesTime dateTimes;
    }
    
    [XmlRoot]
    public class DatesTime
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
    }

    [XmlRoot]
    public class Shift
    {
        [XmlElement("Title")]
        public string Title { get; set; }
        [XmlElement("TitleNoNumber")]
        public string TitleNoNumber { get; set; }
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Number")]
        public Number Numbers;
        [XmlElement("DefaultOption")]
        public int DefaultOption { get; set; }
        [XmlElement("DefaultCheckedYesNoShift")]
        public int DefaultCheckedYesNoShift { get; set; }
    }

    [XmlRoot]
    public class Number
    {
        [XmlElement("Param")]
        [XmlElement(IsNullable = false)]
        public string[] Param = new string[50];
    }
    [XmlRoot]
    public class BootleType
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Item")]
        public Item Items;
    }

    [XmlRoot]
    public class Item
    {
        [XmlElement("Param")]
        [XmlElement(IsNullable = false)]
        public Param Params;
    }

    [XmlType("Param")]
    public class Param
    {
        [XmlAttribute("id")]
        public int Id { get; set; }
    }

    [XmlRoot]
    public class Title
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Text")]
        public string Text { get; set; }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<Document>
	<Position_TopLeft>0</Position_TopLeft>
	<Width>825</Width>
	<Height>630</Height>
	<Title>
		<PosY>0</PosY>
		<Text>TEXT</Text>
	</Title>
	<BootleType>
		<PosY>150</PosY>
		<Item>
			<Param id="0">PIERWSZY</Param>
			<Param id="1">DRUGI</Param>
			<Param id="2">TRZECI</Param>
			<Param id="3">CZWARTY</Param>
			<Param id="4">PIĄTY</Param>
			<Param id="5">SZÓSTY</Param>
			<Param id="6">SIÓDMY</Param>
			<Param id="7">ÓSMY</Param>
			<Param id="8">DZIEWIĄTY</Param>
		</Item>
	</BootleType>
	<Shift>
		<Title>ZMIANA</Title>
		<TitleNoNumber>ZMIANA ....</TitleNoNumber>
		<PosY>330</PosY>
		<Number>
			<Param id="0">I</Param>
			<Param id="1">II</Param>
			<Param id="2">III</Param>
		</Number>
		<DefaultOption>0</DefaultOption>
		<DefaultCheckedYesNoShift>0</DefaultCheckedYesNoShift>
	</Shift>
	<DatesTime>
		<PosY>530</PosY>
	</DatesTime>
</Document>
0

Tak powinny wyglądać klasy

[XmlRoot("Document")]
    public class Document
    {
        [XmlElement("PositionTopLeft")]
        public int PositionTopLeft { get; set; }
        [XmlElement("Width")]
        public int Width { get; set; }
        [XmlElement("Height")]
        public int Height { get; set; }
        [XmlElement("Title")]
        public Title Titles;
        [XmlElement("BootleType")]
        public BootleType BootleTypes { get; set; }
        [XmlElement("Shift")]
        public Shift Shifts { get; set; }
        [XmlElement("DatesTime")]
        public DatesTime DateTime { get; set; }
    }

   
    public class DatesTime
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
    }

    
    public class Shift
    {
        [XmlElement("Title")]
        public string Title { get; set; }
        [XmlElement("TitleNoNumber")]
        public string TitleNoNumber { get; set; }
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Number")]
        public Number Numbers;
        [XmlElement("DefaultOption")]
        public int DefaultOption { get; set; }
        [XmlElement("DefaultCheckedYesNoShift")]
        public int DefaultCheckedYesNoShift { get; set; }
    }


    public class Number
    {
        [XmlElement("Param")]
        public List<Param> Params { get; set; }
    }

    public class BootleType
    {       
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Item")]
        public Item Items { get; set; }
    }

    
    public class Item
    {
        [XmlElement("Param")]
        public List<Param> Params { get; set; }
    }

        
   public class Param
    {
     [XmlAttribute("id")]
     public int Id { get; set; }
     [XmlText]
     public string Name { get; set; }
   }

    
    public class Title
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Text")]
        public string Text { get; set; }
    }

0
szydlak napisał(a):

Tak powinny wyglądać klasy

[XmlRoot("Document")]
    public class Document
    {
        [XmlElement("PositionTopLeft")]
        public int PositionTopLeft { get; set; }
        [XmlElement("Width")]
        public int Width { get; set; }
        [XmlElement("Height")]
        public int Height { get; set; }
        [XmlElement("Title")]
        public Title Titles;
        [XmlElement("BootleType")]
        public BootleType BootleTypes { get; set; }
        [XmlElement("Shift")]
        public Shift Shifts { get; set; }
        [XmlElement("DatesTime")]
        public DatesTime DateTime { get; set; }
    }

   
    public class DatesTime
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
    }

    
    public class Shift
    {
        [XmlElement("Title")]
        public string Title { get; set; }
        [XmlElement("TitleNoNumber")]
        public string TitleNoNumber { get; set; }
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Number")]
        public Number Numbers;
        [XmlElement("DefaultOption")]
        public int DefaultOption { get; set; }
        [XmlElement("DefaultCheckedYesNoShift")]
        public int DefaultCheckedYesNoShift { get; set; }
    }


    public class Number
    {
        [XmlElement("Param")]
        public List<Param> Params { get; set; }
    }

    public class BootleType
    {       
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Item")]
        public Item Items { get; set; }
    }

    
    public class Item
    {
        [XmlElement("Param")]
        public List<Param> Params { get; set; }
    }

        
   public class Param
    {
     [XmlAttribute("id")]
     public int Id { get; set; }
     [XmlText]
     public string Name { get; set; }
   }

    
    public class Title
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Text")]
        public string Text { get; set; }
    }

O właśnie nie wiedziałem jak zdefiniować wywołanie jako pole Param odnosząc się do klasy Param oraz że trzeba było dodać właściwość Name w tej klasie Param. Dziękuje za podpowiedź. A czy mógłbyś podać przykład jak Wywołać to

public List<Param> Params { get; set; }
0

Ale co chcesz wywołać? To jest lista obiektów Param. Możesz wyszukać, iterować. Nie wiem co masz na myśli

0
szydlak napisał(a):

Ale co chcesz wywołać? To jest lista obiektów Param. Możesz wyszukać, iterować. Nie wiem co masz na myśli

No zawartość tej listy chce zobaczyć np na ekran. W sumie sprawdzałem o co chodzi z tym List<T>.
Niestety dalej nie działa mi to rozwiązanie co podałeś. Wciąż te same błędy error :(

Napisałem przykład Listy:

using System;
using System.Collections.Generic;

public class Item{
public List<Param> Params {get; set;}
}
public class Param{
public int Id {get; set;}
public string Name {get; set;}
public override string ToString(){
  return "Id: "+Id+" Name: "+Name;
}
}

class MainClass {
public static void Main (string[] args) {

Item items = new Item();
items.Params = new List<Param>();
items.Params.Add(new Param() {Id=0, Name="Ala"});
items.Params.Add(new Param() {Id=1, Name="Ola"});
items.Params.Add(new Param() {Id=2, Name="Ela"});
items.Params.Add(new Param() {Id=3, Name="Ula"});
Console.WriteLine();
foreach (Param aParam in items.Params)
{
Console.WriteLine(aParam);
}
Console.WriteLine ("Hello World");
}
}

A wynikiem jest:

Id: 0 Name: Ala
Id: 1 Name: Ola
Id: 2 Name: Ela
Id: 3 Name: Ula
Hello World

Może się komuś przyda w zrozumieniu class względem obiektu listy.
Nie wiem tylko gdzie diabeł siedzi mi w kodzie i wciąż nie działa mi :(

0

Pokaż cały kod co Ci nie działa. Ja to co Ci wkleiłem na forum sprawdzałem z xmlem, które dałeś w pierwszym poście. I wszystko działa i się deserializuje na obiekt Document.
Być może:

  1. Twój xml wygląda inaczej
  2. Źle przepisałeś kod
  3. Twój program nie odczytuje w ogóle pliku xml
0
szydlak napisał(a):

Pokaż cały kod co Ci nie działa. Ja to co Ci wkleiłem na forum sprawdzałem z xmlem, które dałeś w pierwszym poście. I wszystko działa i się deserializuje na obiekt Document.
Być może:

  1. Twój xml wygląda inaczej
  2. Źle przepisałeś kod
  3. Twój program nie odczytuje w ogóle pliku xml

Sprawdzę to jutro i Ci powiem wtedy co i jak.

0

document.xml

<?xml version="1.0" encoding="utf-8" ?>
<Document>
	<Position_TopLeft>0</Position_TopLeft>
	<Width>825</Width>
	<Height>630</Height>
	<Title>
		<PosY>0</PosY>
		<Text>TEXT</Text>
	</Title>
	<BootleType>
		<PosY>150</PosY>
		<Item>
			<Param id="0">1</Param>
			<Param id="1">2</Param>
			<Param id="2">3</Param>
			<Param id="3">4</Param>
			<Param id="4">5</Param>
			<Param id="5">6</Param>
			<Param id="6">7</Param>
			<Param id="7">8</Param>
			<Param id="8">9</Param>
		</Item>
	</BootleType>
	<Shift>
		<Title>ZMIANA</Title>
		<TitleNoNumber>ZMIANA ....</TitleNoNumber>
		<PosY>330</PosY>
		<Number>
			<Param id="0">I</Param>
			<Param id="1">II</Param>
			<Param id="2">III</Param>
		</Number>
		<DefaultOption>0</DefaultOption>
		<DefaultCheckedYesNoShift>0</DefaultCheckedYesNoShift>
	</Shift>
	<DatesTime>
		<PosY>530</PosY>
	</DatesTime>
</Document>

Xml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace XMLIK
{
    [XmlRoot("Document")]
    public class Document
    {
        [XmlElement("PositionTopLeft")]
        public int PositionTopLeft { get; set; }
        [XmlElement("Width")]
        public int Width { get; set; }
        [XmlElement("Height")]
        public int Height { get; set; }
        [XmlElement("Title")]
        public Title Titles;
        [XmlElement("BootleType")]
        public BootleType BootleTypes { get; set; }
        [XmlElement("Shift")]
        public Shift Shifts { get; set; }
        [XmlElement("DateTime")]
        public DatesTime DateTime { get; set; }
    }
    
    //[XmlRoot]
    public class DatesTime
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
    }

    //[XmlRoot]
    public class Shift
    {
        [XmlElement("Title")]
        public string Title { get; set; }
        [XmlElement("TitleNoNumber")]
        public string TitleNoNumber { get; set; }
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Number")]
        public Number Numbers { get; set; }
        [XmlElement("DefaultOption")]
        public int DefaultOption { get; set; }
        [XmlElement("DefaultCheckedYesNoShift")]
        public int DefaultCheckedYesNoShift { get; set; }
    }

    //[XmlRoot]
    public class Number
    {
        [XmlElement("Param")]
        [XmlElement(IsNullable = false)]
        public List<Param> Params { get; set; }
    }
    //[XmlRoot]
    public class BootleType
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Item")]
        public Item Items { get; set; }
    }

    //[XmlRoot]
    public class Item
    {
        [XmlElement("Param")]
        [XmlElement(IsNullable = false)]
        public List<Param> Params { get; set; }
    }

    //[XmlType("Param")]
    public class Param
    {
        [XmlAttribute("id")]
        public int Id { get; set; }
        [XmlText]
        public string Name { get; set; }
    }

    //[XmlRoot]
    public class Title
    {
        [XmlElement("PosY")]
        public int PosY { get; set; }
        [XmlElement("Text")]
        public string Text { get; set; }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace XMLIK
{
    public partial class Form1 : Form
    {
        private XmlSerializer xs;
        private List<Document> ls;
        private readonly string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        private string XmlPath { get; set; }
        //private XmlTextReader reader = null;
        protected void LoadXML(string filename)
        {
            try
            {
                XmlPath = filename;
                /*reader = new XmlTextReader(XmlPath);
                reader.MoveToContent();
                String ElementName = "";
                String SubElementName = "";
                if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "document"))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            ElementName = reader.Name;
                        }
                    }
                }*/
                ls = new List<Document>();
                xs = new XmlSerializer(typeof(List<Document>));
                //xmlSerializer.UnknownNode += new XmlNodeEventHandler(XmlSerializer_UnknownNode);
                //xmlSerializer.UnknownAttribute += new XmlAttributeEventHandler(XmlSerializer_UnknownAttribute);
                FileStream reader = new FileStream(XmlPath, FileMode.Open, FileAccess.Read);
                ls = (List<Document>)xs.Deserialize(reader);
                reader.Close();
                //MessageBox.Show("TEST", "TEST", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        protected void XmlSerializer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            MessageBox.Show("Unknown Node:" + e.Name + "\t" + e.Text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        protected void XmlSerializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            System.Xml.XmlAttribute attr = e.Attr;
            MessageBox.Show("Unknown attribute " +
            attr.Name + "='" + attr.Value + "'", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            var fieVersionInfo = FileVersionInfo.GetVersionInfo(executingAssembly.Location);
            var version = fieVersionInfo.FileVersion;
            Text = "XMLik v." + version;
            LoadXML(appPath + "\\" + "document.xml");
            //MessageBox.Show(appPath + "\\" + "document.xml", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

Zaznaczam że używam Visual Studio 2019!

Dalej mam problem z odczytaniem serializacji do zmiennej ls a na zmiennej xs przechodzi debuger do catch ex i wyświetla MessageBox-a z Error-em? co jest nie tak? Skoro tak napisane działa komuś, przykład tutaj:

0

No to pytanie czy twój plik XML ma więcej sekcji <Document> czy tylko jedną? Bo deserializujesz liste

0
szydlak napisał(a):

No to pytanie czy twój plik XML ma więcej sekcji <Document> czy tylko jedną? Bo deserializujesz liste

Jak uruchamiam kompilacje i program to czepia się o <Document xmlns=
Gdzie ja czegoś takiego nie mam w plikach.

0

Mam problem z serializacją i deserializacją tego pliku XML ktoś może pomóc?

screenshot-20191130010457.png

1 użytkowników online, w tym zalogowanych: 0, gości: 1