views:

47

answers:

2

It seems I am having a bit of trouble with Linq to XML, I have looked for tutorials, but nothing really tells me about from, select, statements. I would like to know how to do a foreach/if statements with linq, if you have a tutorial please let me know. My problem right now is I only want a certain part put into my XML if the textbox has something in it.

The code obviously does not work as you cannot put if statements withing my XDocument. Any help/explanation would be very great

if(txtPr3_Chain.Text != "")
                            {
                        new XElement("Property_Info",
                          new XAttribute("Chain", txtPr3_Chain.Text),  
                        new XElement("City" ,txtPr3_City.Text ),
                        new XElement("AdRating" ,AdRating3.CurrentRating.ToString()),
                        new XElement("YourRating" ,YourRating3.CurrentRating.ToString() ),
                        new XElement("Comment" ,txtPr3_Comments.Text)),
                            }
+2  A: 

Are you simply attempting to construct a new XElement when the Text value is not empty?

Try this:

XElement element = null;
if (txtPr3_Chain.Text != "")
{
    element = new XElement("Property_Info",
                            new XAttribute("Chain", txtPr3_Chain.Text),
                            new XElement("City", txtPr3_City.Text),
                            new XElement("AdRating", AdRating3.CurrentRating.ToString()),
                            new XElement("YourRating", YourRating3.CurrentRating.ToString()),
                            new XElement("Comment", txtPr3_Comments.Text));
}
Wallace Breza
thanks this works, though for the future, I will be doing more foreach type loops, within the Xdocument... if you have any tutorials that would be great, as I can't seem to find any good ones
Spooks
+2  A: 

Why not create the XDocument with the parts that are always there and then insert/append the other parts after, where you can use a regular for or if

Sruly
thanks, this worked with the combo of the first answer, thanks!
Spooks