简体   繁体   English

Linq to XML if / foreach with XElement

[英]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. 似乎我对Linq to XML有点麻烦,我一直在寻找教程,但是关于select语句并没有真正告诉我。 I would like to know how to do a foreach/if statements with linq, if you have a tutorial please let me know. 我想知道如何使用linq进行foreach / if语句,如果您有教程,请告诉我。 My problem right now is I only want a certain part put into my XML if the textbox has something in it. 我现在的问题是,如果文本框中包含某些内容,我只希望将其放入XML中。

The code obviously does not work as you cannot put if statements withing my XDocument. 该代码显然无法正常工作,因为无法将if语句与我的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? 您是否只是在Text值不为空时尝试构造新的XElement

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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