开发者

Linq to XML if/foreach with XElement

开发者 https://www.devze.com 2023-01-10 05:18 出处:网络
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 w

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));
}


  1. It is not a bad idea to always include all those nodes, even when they're empty

  2. 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());
0

精彩评论

暂无评论...
验证码 换一张
取 消