Click here to Skip to main content
15,072,776 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi i have a problem, i want to get my xmlnodelist inside my xmlnode foreach somehowe because i have counter on it, an i need to get the of addon attribute match the id of textbox and nodes.
My final goal is a shooping basket. Where i count the number in the textbox and counting, it with the price that comes from an xmlnode called AddonPrice.
Right now i only get the first addon not the two others, so it looks like this right now.

Type:Ticket counts:1 price:178 total price: 178

and the counting works fine, but only with the first node. I think my problem is this line doc.SelectNodes("TourInfo/AddOns/AddOn[@Id='" + id + "']");. Because its outside my foreach so the id count will allways be 0. So i need help to get it inside my foreach or, do it some other way :)

C#
string id = "addon" + count;
        string addon;
                
        XmlNodeList nodeListADDon = doc.SelectNodes("TourInfo/AddOns/AddOn[@Id='" + id + "']");
        litTotal.Text = "";
        litAdd.Text = "";
        foreach (XmlNode nodeA in nodeListADDon)
        {
         
            addon = Request.Form["txtAddonAntal" + count];
            antal = int.Parse(addon.ToString());

            pris = int.Parse(nodeA["AddonPrice"].InnerText);
            ansver += antal * pris;
           total += ansver;

            litTotal.Text += total.ToString() + " kr";
            litAdd.Text = "<table class="table table-condensed"><tr>" + "<td>" + nodeA["AddonText"].InnerText + "</td>" + "<td>" + antal.ToString() + "</td>" + "<td>Pris:&nbsp;" + ansver.ToString() + "&nbsp;kr</td>" + "</tr></table><br />";
            count++;
        }



EDIT
XML
<?xml version="1.0" standalone="no"?>
<!-- 0031114_reply.xml - generated by ACUCOBOL-GT v9.2.3 + ECN-4310 + ECN-4314 + ECN-4316 on 2015/06/25 -->
<TourInfo>
  <Recordtype>TourInfo</Recordtype>
  <Trip>1609</Trip>
  <TransportForm>2</TransportForm>
  <Accommodation>200</Accommodation>
  <AvailableTrips>14</AvailableTrips>
  <AddOns>
    <AddOn Id="addon0">
      <AddonCode>1</AddonCode>
      <AddonText>Barnestol</AddonText>
      <AddonAccNo>200</AddonAccNo>
      <AddonPrice>150</AddonPrice>
      <AddonPriceOffersText>Tilbud:</AddonPriceOffersText>
      <AddonPriceOffers>125</AddonPriceOffers>
    </AddOn>
    <AddOn Id="addon1">
      <AddonCode>2</AddonCode>
      <AddonText>Tremmeseng</AddonText>
      <AddonAccNo>200</AddonAccNo>
      <AddonPrice>200</AddonPrice>
      <AddonPriceOffersText />
      <AddonPriceOffers />
    </AddOn>
    <AddOn Id="addon2">
      <AddonCode>9</AddonCode>
      <AddonText>Billet</AddonText>
      <AddonAccNo>67</AddonAccNo>
      <AddonPrice>178</AddonPrice>
      <AddonPriceOffersText />
      <AddonPriceOffers />
    </AddOn>
  </AddOns>
Posted
Updated 24-Jun-15 23:44pm
v4
Comments
Andy Lanng 24-Jun-15 4:21am
   
I don't get what you're trying to do. Please use the "Improve Question" button above this comment and go into a bit more detail.
Please include your ultimate goal, your current intention (which is the bit you have included) and why you cannot achieve your stated goal.

Thanks ^_^
Andy Lanng 24-Jun-15 4:41am
   
Great job. Much better ^_^
I remember this one :D

1 solution

Ok - I see:

You are correct. The list nodelist is only iterated once for 1 id. Try wrapping this in a for loop:

if the id is being iterated


C#
for(int x= 0;x<doc.SelectNodes("TourInfo/AddOns/AddOn").Count;x++)
{

        string addon;
                
        XmlNodeList nodeListADDon = doc.SelectNodes("TourInfo/AddOns/AddOn[@Id='addon" + x + "']");
        litTotal.Text = "";
        litAdd.Text = "";
        foreach (XmlNode nodeA in nodeListADDon)
        {
         
            addon = Request.Form["txtAddonAntal" + x];
            antal = int.Parse(addon.ToString());
 
            pris = int.Parse(nodeA["AddonPrice"].InnerText);
            ansver += antal * pris;
           total += ansver;
 
            //Formatted for clarity
            litTotal.Text += total.ToString() + "&nbsp;kr";
            string text = "<table class="table table-condensed"><tr>" 
            text += "<td>" + nodeA["AddonText"].InnerText + "</td>" 
            text += "<td>" + antal.ToString() + "</td>" 
            text += "<td>Pris:&nbsp;" + ansver.ToString() 
            text += "&nbsp;kr</td>" 
            text += "</tr></table><br />";

            litAdd.Text = text;

        }
}




UPDATE: I now have access to the OP source and code:


C#
private static void testsss()
{
    XmlDocument doc = new XmlDocument();
    doc.Load(@"C:\3rd Party\testsss.xml");

    int total = 0;

    litTotal.Text = "";
    litAdd.Text = "";

    //Error handling
    var allAddonNodes = doc.SelectNodes("TourInfo/AddOns/AddOn");
    if (allAddonNodes == null)
        return;

    for (int x = 0; x < allAddonNodes.Count; x++)
    {
        string textBoxname = string.Format("txtAddonAntal{0}", x);

        XmlNode addonNode = allAddonNodes[x];
        //Error handling
        if (addonNode["AddonPrice"] == null)
            continue;

        //Error handling
        int antal;
        if (!int.TryParse(Request.Form[textBoxname], out antal))
            continue;

        //Error handling
        int pris;
        if (!int.TryParse(addonNode["AddonPrice"].InnerText, out pris))
            continue;

        var ansver = antal * pris;
        total += ansver;


        var nodeAAddonText = addonNode["AddonText"];

        string nodeAInnerText = nodeAAddonText == null ? "" : nodeAAddonText.InnerText;

        //This line seems out of place
        litAdd.Text = string.Format(FormatText, nodeAInnerText, antal, ansver);

    }
    litTotal.Text = total + @"&nbsp;kr";
}




FINAL UPDATE: Some ideas about litAdd:

private static void testsss()
{
    //If you have a table included in the markup then run that at server
    //and use that instead.  The method below is a bit of a hack.

    //We'll use this to write the table markup to a string.  This is the hack part
    StringBuilder sb = new StringBuilder();
    HtmlTextWriter writer = new HtmlTextWriter( new StringWriter(sb,CultureInfo.InvariantCulture));

    //table to use in the hack
    HtmlTable table = new HtmlTable();
    table.Attributes.Add("class", "table table-condensed");



    XmlDocument doc = new XmlDocument();
    doc.Load(@"C:\3rd Party\testsss.xml");

    int total = 0;

    litTotal.Text = "";
    litAdd.Text = "";

    //Error handling
    var allAddonNodes = doc.SelectNodes("TourInfo/AddOns/AddOn");
    if (allAddonNodes == null)
        return;

    for (int x = 0; x < allAddonNodes.Count; x++)
    {
        //create a new table row
        HtmlTableRow row = new HtmlTableRow();
        // a cell instance to add to the row.
        HtmlTableCell cell;

        string textBoxname = string.Format("txtAddonAntal{0}", x);

        XmlNode addonNode = allAddonNodes[x];
        //Error handling
        if (addonNode["AddonPrice"] == null)
            continue;

        //Error handling
        int antal;
        if (!int.TryParse(RequestForm[textBoxname], out antal))
            continue;

        //Error handling
        int pris;
        if (!int.TryParse(addonNode["AddonPrice"].InnerText, out pris))
            continue;

        var ansver = antal * pris;
        total += ansver;


        var nodeAAddonText = addonNode["AddonText"];

        string nodeAInnerText = nodeAAddonText == null ? "" : nodeAAddonText.InnerText;

        cell = new HtmlTableCell();
        cell.InnerText = nodeAInnerText;
        row.Cells.Add(cell);

        cell = new HtmlTableCell();
        cell.InnerText = antal.ToString();
        row.Cells.Add(cell);

        cell = new HtmlTableCell();
        cell.InnerText = string.Format("Pris:&nbsp;{0}&nbsp;kr", ansver);
        row.Cells.Add(cell);

        //add the row to the table
        table.Rows.Add(row);

    }

    //if the table exists already, then the page render will draw it, the rows and the cells
    //when the page is rendered.  In this hack it is not in the page so we have to render it
    //ourselves and get the html.  This is a hack (but a good one ;)

    table.RenderControl(writer);

    litAdd.Text = sb.ToString();

    litTotal.Text = total + @"&nbsp;kr";
}
   
v8
Comments
Martin Lauritsen 24-Jun-15 5:04am
   
thx m8 i only get one last thing, before i can try it out.
This line for(int x= 0;x<("TourInfo/AddOns/AddOn").Count();x++) my problem is "Count" it says that string does not contain a defintion for 'Count' and no extension method of count exists " in Visuel studio". I have try to wrap it in an string and int
Andy Lanng 24-Jun-15 5:41am
   
It's just an example. int x has replaced int count. Did that have a max value? If so then replace that line with for(int x = countstart;x<countmax;x++)
Martin Lauritsen 25-Jun-15 4:19am
   
hey no i doesnt have a max value, my line looks like this
for(int count = 0;count<("TourInfo/AddOns/AddOn").Count();count++), but im not sure what i should do with this .Count() :)
Andy Lanng 25-Jun-15 4:27am
   
oh right. Count is a property, not a method:
or(int count = 0;count<("TourInfo/AddOns/AddOn").Count;count++)
Note that the brackets have been removed

This will work ^_^
Martin Lauritsen 25-Jun-15 4:30am
   
hmm nope it still says, that string does not contain a definition and no extensin method for count. Should i define it in a string, or create a method? :)
Martin Lauritsen 25-Jun-15 4:54am
   
i put doc.selectNodes in front of ("TourInfo/AddOns/AddOn") it removed the red lin under Count. Bot it does not work on page :)
Martin Lauritsen 25-Jun-15 5:08am
   
for(int count = 0;count< doc.SelectNodes("TourInfo/AddOns/AddOn").Count;count++) does not make error but it is making empty string in litAdd. Is it because im using xmlnodelist in foreach?
Martin Lauritsen 25-Jun-15 5:11am
   
entire code right now

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("./xmlRe/" + filenDato + ".xml"));

int antal = 0;
int ansver = 0;
int pris;
int total = 0;


string addon = "";
string add = "addon";
litTotal.Text = "";
litAdd.Text = "";

for(int count = 0;count< doc.SelectNodes("TourInfo/AddOns/AddOn").Count;count++)
{



XmlNodeList nodeListADDon = doc.SelectNodes("TourInfo/AddOns/AddOn[@Id='addon" + add + count + "']");

foreach (XmlNode nodeA in nodeListADDon)
{

addon = Request.Form["txtAddonAntal" + count];
antal = int.Parse(addon.ToString());

pris = int.Parse(nodeA["AddonPrice"].InnerText);
ansver += antal * pris;
total += ansver;

//Formatted for clarity
litTotal.Text += total.ToString() + " kr";
string text = @"<table class='table table-condensed'>
<tr>" +"<td>" + nodeA["AddonText"].InnerText + "</td>" +
"<td>" + antal.ToString() + "</td>" +
"<td>Pris: " + ansver.ToString() + " kr</td>" +
"</tr></table><br />";

litAdd.Text = text;

}
Andy Lanng 25-Jun-15 5:15am
   
ok - you were correct about my code missing doc.SelectNodes.

Could you also post your xml. It might help me figure out what you're trying to do
Martin Lauritsen 25-Jun-15 5:23am
   
<tourinfo>
<recordtype>TourInfo
<Trip>1609</Trip>
<TransportForm>2</TransportForm>
<accommodation>200
<availabletrips>14
<addons>
<addon id="addon0">
<addoncode>1
<addontext>Barnestol
<addonaccno>200
<addonprice>150
<addonpriceofferstext>Tilbud:
<addonpriceoffers>125

<addon id="addon1">
<addoncode>2
<addontext>Tremmeseng
<addonaccno>200
<addonprice>200
<addonpriceofferstext>
<addonpriceoffers>

<addon id="addon2">
<addoncode>9
<addontext>Billet
<addonaccno>67
<addonprice>178
<addonpriceofferstext>
<addonpriceoffers>

Martin Lauritsen 25-Jun-15 5:24am
   
it removes the <addons><addon id="addon0">
Martin Lauritsen 25-Jun-15 5:31am
   
i made a url to image of the file http://tinypic.com/view.php?pic=34oap1d&s=8#.VYvKSPntlBc :)
Andy Lanng 25-Jun-15 5:40am
   
ha ha ha ^_^ you've been got by the tag demon
Click "Improve Question" button below your original question

At the bottom, write "EDIT: Added Source XML below"
Paste the xml - this should come up with several paste options on the right.
Choose paste as code
That will correct the tags for you and allow the post to look at it should :D
Martin Lauritsen 25-Jun-15 5:45am
   
haha thanks, and thanks for taking you time to help me ;)
Andy Lanng 25-Jun-15 6:21am
   
NP. Your code has become confused. Please take a look the the solution update. I have radically changed the format of your code but I think I have kept the logic.

There is one line that looks out-of-place: litAdd.Text = ...
This text will always only equal the last addon. What should be displayed here?
Martin Lauritsen 25-Jun-15 6:24am
   
litAdd should show the basket, you know items and prices
Andy Lanng 25-Jun-15 6:28am
   
ah - I see.

Your doing it wrong :P

You can add rows and columns to an extant table from code-behind. It's easier that the way you are doing it because you don't have to write out lit html each time.

I'll rewrite and post a couple of options.

In the mean time, try to implement the code I have posted. Other than that one line (which I'll update) it should be MUCH closer to what you need
Martin Lauritsen 25-Jun-15 6:32am
   
It WORKS!!!. i can now see what yu mean with litAdd that it replaces the strign everytime. I am so gald that you could help me Andy, im really thankfull
Andy Lanng 25-Jun-15 6:43am
   
Yeah, it really helps if we understand what you are trying to do. Take a look at your original question (version 1) and see how difficult it would be to answer that :P

but wait for it: here come the masterpiece hack - check solution :)

PS: don't forget to accept the solution
Martin Lauritsen 25-Jun-15 7:13am
   
Thank you so much, i learn so much today :) It works it all, like a pro :). Now i can play with the code and put the next node on :)
Andy Lanng 25-Jun-15 7:14am
   
Great! I'm glad you took so much from this. Hopefully you'll be posting solutions soon ^_^
Martin Lauritsen 25-Jun-15 7:20am
   
i hope so, you just learned me a new way to do things :) and now i know where to find you if i ever "f*** up in my code again" :) Thanx again for the replies
Martin Lauritsen 26-Jun-15 3:53am
   
I got one last question for you Andy, if i want add and ekstra set off nodes that lay in a diffrent parent node, can i implement them in the same for loop, or should i create a new loop :)
Andy Lanng 26-Jun-15 4:06am
   
If they lie outside of "Addons" then you should create a new loop.
If the enumerations are identical (i.e. 5 addons = 5 of this new node) then iterating through them in a separate loop makes your code easier to read and therefore maintain
Martin Lauritsen 26-Jun-15 4:11am
   
thanks i will try, just wanted to ask before you i did anything wrong :)
Andy Lanng 26-Jun-15 4:19am
   
np :)

Your question was entirely related to this thread so you went about asking the right way IMHO. If you need any related help then consider posting a new question :D
Martin Lauritsen 26-Jun-15 4:51am
   
cool im new to this site as you can see ;) i got it to work the only problem is it picks the last node only, and its the same method as before with a txtbox that starts with id=0 and a node text starts with id=0. but i can only use the last one, if i write a number in txtbox0 it just makes i bumb and nothing happens. But if i take the last oom and write a number it does it the right way. I can write a new question if you want? :)
Martin Lauritsen 26-Jun-15 4:22am
   
yes i think i will do, because it going to be a long thread this one. I think now is the next step, because its a pretty big projeckt for me, so i want it to be done the right way :)
Andy Lanng 26-Jun-15 4:43am
   
just remember to hit reply in the comment you are replying to ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900