简体   繁体   中英

Linq to XML if/foreach with XElement

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

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

为什么不使用始终存在的部分创建XDocument,然后在之后可以使用常规的for或if插入/追加其他部分

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM