webForumDet fria alternativet

xml genom serialization

7 svar · 327 visningar · startad av Dino

DinoMedlem sedan sep. 20011 914 inlägg
#1

Tänkte jag skulle jobba lite med xml genom serialization, men behöver en knuff för hur jag skall göra
för att få en xml fil liknande nedan. Behöver alltså tips om upplägget.

<?xml version="1.0" encoding="utf-8"?>
<poll>
  <pollItem id="1">
    <date>2003-03-31 17:26:52</date>
    <caption>Har du bil?</caption>
    <totalvotes>433</totalvotes>
    <options>
      <alt id="1">
        <text>grr</text>
        <votes>213</votes>
      </alt>
      <alt id="2">
        <text>grr</text>
        <votes>111</votes>
      </alt>
      <alt id="3">
        <text>grr</text>
        <votes>69</votes>
      </alt>
    </options>
  </pollItem>
  <pollItem id="2">
    <date>2003-03-31 18:24:21</date>
    <caption>Kan fåglar köra bil?</caption>
    <totalvotes>623</totalvotes>
    <options>
      <alt id="1">
        <text>Ja</text>
        <votes>123</votes>
      </alt>
      <alt id="2">
        <text>Nej</text>
        <votes>43</votes>
      </alt>
      <alt id="3">
        <text>Osäker</text>
        <votes>387</votes>
      </alt>
      <alt id="4">
        <text>Kanske i framtiden</text>
        <votes>9</votes>
      </alt>
      <alt id="5">
        <text>Hmm</text>
        <votes>75</votes>
      </alt>
      <alt id="6">
        <text>Kan inget om fåglar</text>
        <votes>11</votes>
      </alt>
    </options>
  </pollItem>

Har denna classen som behöver byggas ut. Vet inte hur jag skall göra med alternativen, 2 - 10st.
Och att få varje ny fråga till filen att bli en pollItem.

class poll
        public id as integer
        public datetime as date
        public caption as string
        public totalvotes as integer
        
        sub new()
            'nothing new here
        end sub
        
        sub new(byval id as integer, byval datetime as date, byval caption as string, byval totalvotes as integer)
            me.id = id
            me.datetime = datetime
            me.caption = caption
            me.totalvotes = totalvotes
        end sub
    end class

   sub TestXmlSerializer()
        dim ser as new xmlSerializer(GetType(poll))
        dim poll as new poll(1, datetime.now, "Äger du ett tåg?", 532)
        dim fs as new filestream("C:\poll.xml", filemode.create)
        ser.serialize(fs,poll)
        fs.close()
    end sub
DinoMedlem sedan sep. 20011 914 inlägg
#2

Ok, tror jag skall använda mig av xmlattribute och en array för de olika alternativen. Eller...

renholmMedlem sedan apr. 20012 266 inlägg
#3

Ungefär något så här:

[XmlRoot("poll")]
public class poll
{
	private PollCollection polls = new PollCollection(); // skapa en collection som innehåller alla pollItem object, dvs du måste då även skapa en class för pollItem

	[XmlArrayItem(typeof(pollItem))]
	public PollCollection pollItem
	{
		get { return polls}
		set { polls = value; }
	}

	public poll()
	{}
}

public class pollItem
{
	[XmlAttribute]
        public int id;

	[XmlElement]
        public datetime date;

	[XmlElement]
        public string caption;

	[XmlElement]
        public int totalvotes;

	private OptionCollection _options = new OptionCollection(); // skapa en collection för options och en class för varje option

	[XmlArrayItem(typeof(pollItem))]
	public OptionCollection options
	{
		get { return _options; }
		set { _options = value; }
	}

	public pollItem()
	{ }
}

Skapa sedan alt classen utifrån de mönster jag har gjort ovan. Detta funkar för mig, kanske inte smidigast, men väldigt lätt att jobba med då xml filen är speglad i classer.

DinoMedlem sedan sep. 20011 914 inlägg
#4

Tackar så mycket. Nu har jag nåt mer konkret att gå efter, hade själv kommit så här långt.

    class pollitems
        <XmlArray("poll"),XmlArrayItem("pollItem")> public pollitem() as pollitem
    end class
    
    public class pollitem
        <XmlAttributeAttribute("id")> public id as integer
        public [date] as date
        public caption as string
        public totalvotes as integer
        <XmlArray("options"),XmlArrayItem("alt")> public options() as alt        
    end class
    
    public class alt
        <XmlAttributeAttribute("id")> public id as integer
        public text as string
        public votes as integer
    end class
DinoMedlem sedan sep. 20011 914 inlägg
#5

Läste om en sak som kan vara användbar i sammanhanget.
Om ni har ett xml schema(.xsd fil) så gör följande:
1. Öppna kommandotolken och leta er fram till mappen där filen finns.
2. Skriv: xsd filnamn.xsd /c /l:vb
3. Tryck Enter
Nu skapas det en fil med classer som representerar xml schemat.

/c kan bytas ut mot /d för att skapa dataset.
/l:vb kan bytas ut mot /l:cs för C# filer.

renholmMedlem sedan apr. 20012 266 inlägg
#6

Smidigt... testat hur det fungerar?

DinoMedlem sedan sep. 20011 914 inlägg
#7

Jodå, detta schemat som gäller för xml filen från första inlägget.

<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema targetNamespace="http://tempuri.org/pollschema1.xsd"
  xmlns="http://tempuri.org/pollschema1.xsd"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="poll"> 
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="pollItem" maxOccurs="unbounded">
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:element name="date" type="xsd:date"/>
                            <xsd:element name="caption" type="xsd:string"/>
                            <xsd:element name="totalvotes" type="xsd:positiveInteger"/>
                            <xsd:element name="options">
                                <xsd:complexType>
                                    <xsd:sequence>
                                        <xsd:element name="alt" minOccurs="2" maxOccurs="10">
                                            <xsd:complexType>
                                                <xsd:sequence>
                                                    <xsd:element name="text" type="xsd:string"/>
                                                    <xsd:element name="votes" type="xsd:positiveInteger"/>
                                                </xsd:sequence>
                                                <xsd:attribute name="id" type="xsd:positiveInteger" use="required"/>
                                            </xsd:complexType>
                                        </xsd:element>
                                    </xsd:sequence>
                                </xsd:complexType>
                            </xsd:element>    
                        </xsd:sequence>
                        <xsd:attribute name="id" type="xsd:positiveInteger" use="required"/>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>          
</xsd:schema>

ger detta resultat

Option Strict Off
Option Explicit On

Imports System.Xml.Serialization

<XmlTypeAttribute([Namespace]:="http://tempuri.org/pollschema1.xsd"),  _
 XmlRootAttribute("poll", [Namespace]:="http://tempuri.org/pollschema1.xsd", IsNullable:=false)>  _
Public Class poll

    <XmlElementAttribute("pollItem")>  _
    Public pollItem() As pollPollItem
End Class

<XmlTypeAttribute([Namespace]:="http://tempuri.org/pollschema1.xsd")>  _
Public Class pollPollItem

    <XmlElementAttribute(DataType:="date")>  _
    Public [date] As Date

    Public caption As String

    <XmlElementAttribute(DataType:="positiveInteger")>  _
    Public totalvotes As String

    <XmlArrayItemAttribute("alt", IsNullable:=false)>  _
    Public options() As pollPollItemAlt
    
    <XmlAttributeAttribute(DataType:="positiveInteger")>  _
    Public id As String
End Class

<XmlTypeAttribute([Namespace]:="http://tempuri.org/pollschema1.xsd")>  _
Public Class pollPollItemAlt

    Public [text] As String
    
    <XmlElementAttribute(DataType:="positiveInteger")>  _
    Public votes As String
    
    <XmlAttributeAttribute(DataType:="positiveInteger")>  _
    Public id As String
End Class

Ser det ok ut eller?

renholmMedlem sedan apr. 20012 266 inlägg
#8

ser helt okej ut

140 ms totalt · 3 externa anrop · v20260731065814-full.86db40fa
0 ms — hämta forumlista (cache)
0 ms — hämta statistik (cache)
137 ms — hämta tråd, inlägg och bilagor (db)