Deserialization of XML into Multiple Objects of the Same Type (For Windows 8 App)

StackOverflow https://stackoverflow.com/questions/20364630

  •  28-08-2022
  •  | 
  •  

Pregunta

So I'm trying to deserialize the following XML Document into multiple objects of my custom type (ItemModel). Since I'm developing for the Windows 8 platform, I've been hitting a lot of blocks due to library incompatibilities. What I'm trying to do is deserialize each ItemModel into an object than add them to a List of some sort. From what I have, the code runs but the list is not populating.

<?xml version="1.0" encoding="utf-8" ?>

<Items>
  <ItemModel>
    <ID>0</ID>
    <Name>Apple</Name>
    <Category>Compost</Category>
    <ImageWidth>67</ImageWidth>
    <ImageHeight>100</ImageHeight>
    <Description>An Apple is a compost item that....</Description>
    <ImagePath>Graphics\\apple.png</ImagePath>
  </ItemModel>
  <ItemModel>
    <ID>0</ID>
    <Name>Water Bottle</Name>
    <Category>Mixed Containers</Category>
    <ImageWidth>67</ImageWidth>
    <ImageHeight>100</ImageHeight>
    <Description>A Water bottle is a mixed container item that...</Description>
    <ImagePath>Graphics\\Bottle.png</ImagePath>
  </ItemModel>
</Items>

Note: I'm also experiencing some trouble using the XmlReader. It's the reader us equal to null even after I use XmlReader.Create().

Thank you.

¿Fue útil?

Solución

if you are reading from a .xml file and displaying in Web browser and your code behind is C#, you can do something like this :

 protected void Page_Load(object sender, EventArgs e)
 {                 
      ReadXmlFile(Server.MapPath("~/XMLFiles/Items.xml"));
 }

 private void ReadXmlFile(string fileName)
 {
    string parentElementName = "";
    string childElementName = "";
    string childElementValue = "";
    bool element = false;
    lblMsg.Text = "";

    XmlTextReader xReader = new XmlTextReader(fileName);
    while (xReader.Read())
    {
        if (xReader.NodeType == XmlNodeType.Element)
        {
            if (element)
            {
                parentElementName = parentElementName + childElementName + "<br>";
            }
            element = true;
            childElementName = xReader.Name;
        }
        else if (xReader.NodeType == XmlNodeType.Text | xReader.NodeType == XmlNodeType.CDATA)
        {
            element = false;
            childElementValue = xReader.Value;
            lblMsg.Text = lblMsg.Text + "<b>" + parentElementName + "<br>" + childElementName + "</b><br>" + childElementValue;

            parentElementName = "";
            childElementName = "";
        }
    }
    xReader.Close();
  }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top