not sure why invalid cast exception

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TearX
    New Member
    • Dec 2012
    • 6

    not sure why invalid cast exception

    I having problem trying to read from xml file and store it in to my database

    Code:
    nodelist = xmlDoc.GetElementsByTagName("Item");
    ArrayList inlist = new ArrayList();
    foreach (XmlNode Node in nodelist)
     {
     OrderDetail od = new OrderDetail();
     if (Node.Attributes.Count > 0)
     {
     textBox2.Text += "Item_ID = " + Node.Attributes[0].Value + Environment.NewLine;
    od.ItemId = Node.Attributes[0].Value;
    }
     if (Node.HasChildNodes)
    {
     [B]XmlElement ChildNode = (XmlElement)Node.FirstChil[/B]
    (the error is here which is in Bold)
    for (int i = 0; i < Node.ChildNodes.Count; i++)
    {
    switch (ChildNode.Name)
    {
    case "size":
     textBox2.Text += "Size = ";
    od.Size = ChildNode.InnerText;
    break;
    this is my xml file
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <!--This document contains Ordering Information-->
    <OrderList xmlns="http://www.MyCompany.com">
      <Order Order_ID="1" Order_Date="1/2/2013" Buyer_ID="GFS1810">
        <Remark />
        <Item Item_ID="123" Size="M" Color="blue" Quantities="10" ePrice="33.77">Very Nice</Item>
        <Item Item_ID="23423423" Size="M" Color="red" Quantities="10" ePrice="44.10">Please Wear</Item>
        <Item Item_ID="3242" Size="XL" Color="green" Quantities="10" ePrice="67.00">Can Wear</Item>
        <Item Item_ID="3456" Size="S" Color="pink" Quantities="10" ePrice="10.00">SoSo</Item>
      </Order>
      <Order Order_ID="1" Order_Date="1/2/2013" Buyer_ID="GFS1810">
        <Remark />
        <Item Item_ID="4535" Size="L" Color="yellow" Quantities="10" ePrice="22.00">Very Ok</Item>
      </Order>
    </OrderList>
  • Mikkeee
    New Member
    • Feb 2013
    • 94

    #2
    The reason you're getting an invalid cast exception is because there are no "Item" child nodes of XmlElement type. The FirstChild of "Item" is the node's inner text. You might want to consider being a little more strict with your data types to eliminate these issues. I would suggest the following to simplify the code.

    Code:
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
    nsmgr.AddNamespace("ns", "http://www.MyCompany.com");
    
    foreach (XmlNode node in xmlDoc.SelectNodes(@"//ns:OrderList/ns:Order/ns:Item", nsmgr))
    {
        Console.WriteLine(node.Attributes["Item_ID"].InnerText);
        Console.WriteLine(node.Attributes["Size"].InnerText);
    }

    Comment

    • TearX
      New Member
      • Dec 2012
      • 6

      #3
      thank though my friend had taught me another method but your code work

      Comment

      Working...