简体   繁体   中英

How to write XmlSerializable ReadXml for WriteXml with Elements through C# .NET v3.5

I'm not really sure what the right question is to ask here, so I'll do my best to present the scenario.

We've got a ParentObject with a list of Quantity of various dimensions. Let's say ParentObject says it has Length, Duration, etc.

We want to serialize that to and from Xml, necessarily through WriteXml / ReadXml. I've written the WriteXml, not much problem there. Our test output shows something along these lines.

<ParentObject Name="SuchAndSuch">
  <Quantities>
    <Length Value="123.456" />
    <Duration Value="78.9" />
  </Quantities>
</ParentObject>

This is an oversimplification, of course. Point is, we're writing an element out by the name of "Quantities". That's written using WriteStartElement("Quantities") and WriteEndElement(). So far so good.

Now I am writing the ReadXml to read the thing back in and necessarily re-constitute the object. I am receiving an error something like "Element 'Quantities' not found" when I try and ReadStartElement("Quantities").

There are notes I'm studying about moving to nodes and the current node. Up to that point I've used GetAttribute() and that's it. So as far as I can tell, our reader is still at a starting position, perhaps?

Is there a better way to read through elements or otherwise position the reader so it can read our Quantites?

Thanks...

This may not answer your question directly, but instead of writing your own code to write and read the XML, why not use System.Xml.Serialization.XmlSerializer to do all the work for you?

I've only recently discovered it myself and have used it backup and restore lots of data fetched from a web service.

Example based on code I've used (Stuff = ParentObject):

Stuff stuff = FunctionToCreateStuff();
StreamWriter writer = new StreamWriter("stuff.xml");
x = new System.Xml.Serialization.XmlSerializer(stuff.GetType());
x.Serialize(writer, stuff);
writer.Close();

StreamReader reader = new StreamReader("stuff.xml");
x = new System.Xml.Serialization.XmlSerializer(typeof(Stuff));
Stuff stuff = (Stuff)x.Deserialize(reader);
reader.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM