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 sta开发者_开发百科tements 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)),
}
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
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));
}
It is not a bad idea to always include all those nodes, even when they're empty
If you insist, you can write an enumerator-method that yields non-empty fields:
//untested
IEnumerable<Xelement> GetFields()
{
if (txtPr3_City.Text != null)
yield return new Xelement("City",txtPr3_City.Text);
....
}
element = new XElement("Property_Info",
new XAttribute("Chain", txtPr3_Chain.Text),
GetFields());
精彩评论