0

I am trying to iterate every element under PcsInItem and get Price for each and insert them into SQL table. Below is my XML structure.

        <Message>
            <Body>
                <Item Id="8683297523">
                    <PcsInItem>
                        <Pcs Price="20" PcsId="12829"></Pcs>
                        <Pcs Price="50" PcsId="64838"></Pcs>
                        <Pcs Price="80" PcsId="43829"></Pcs>
                    </PcsInItem>
                </Item>
            </Body>
        </Message>

When i run the code, it only inserts first item into SQL. I couldn't figure out why it does not iterate other items as well and only getting the first one.

This is my code:

var xdoc = XDocument.Parse(soapResult);
var y = xdoc.Descendants("Body").Descendants("PcsInItem");

var a = xdoc.Descendants("Body");
XElement b = a.Elements("Item").Last();
var ItemId = b.Attributes("Id").FirstOrDefault().Value;

SqlConnection conn;
string constring = @"...";
string query = "INSERT INTO..";

using (conn = new SqlConnection(constring))
{
    foreach (XElement x in y)
    {
        var Price = x.Element("Pcs").Attribute("Price")?.Value;
        var PcsId = x.Element("Pcs").Attribute("PcsId")?.Value;
        using (var cmd = new SqlCommand(query, conn))
        {
            try
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@Price", Price);
                cmd.Parameters.AddWithValue("@PcsId", PcsId);
                cmd.Parameters.AddWithValue("@ItemId", ItemId);
                komut2.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

Any idea why i am only getting first item in my SQL table? There should be 3 different table record and all these three record have same ItemId bu different Price and PcsId.

thatthing
  • 676
  • 3
  • 15
  • 39
  • 2
    There is only one "PcsInItem". Check your `y` var. It should be a collection of size 1. So, there is only one x. You need to iterate its _children_ though. – Fildor Apr 28 '20 at 07:37
  • 1
    @Fildor Oh shoot! I think you are right. It's working now. Thank you! – thatthing Apr 28 '20 at 07:46

0 Answers0