XElement对象上的条件逻辑 [英] Conditional Logic on XElement objects

查看:69
本文介绍了XElement对象上的条件逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用XmlWriter时,我会检查数据以确定编写者是否应该编写一个元素,然后以这种方式连续构建一个XML元素树:

When using XmlWriter I check for data to determine if the writer should write an element or not and do it this way to successively build a tree of XML elements:

string title = ItemTitleTextBox.Text;
$
string link = ItemLinkTextBox.Text;

string title = ItemTitleTextBox.Text;
string link = ItemLinkTextBox.Text;

if(!String.IsNullOrEmpty(title))

  writer1.WriteElementString(" title",title);
$
if(!String.IsNullOrEmpty(link))

writer1.WriteElementString(" link",link);

...

...

if(!String.IsNullOrEmpty(title))
  writer1.WriteElementString("title", title);
if(!String.IsNullOrEmpty(link))
writer1.WriteElementString("link", link);
...
...



有人可以给我一个片段或链接在一篇文章中展示了如何在使用XElements构建XML元素树时这样做?我尝试在XElement中使用条件逻辑("title",[逻辑此处]),但这会导致错误。


Can somebody give me a snippet or a link to an article to show how to do so when using XElements to build a tree of XML elements? I tried to use conditional logic inside XElement("title", [logic here] ) but that caused an error.

推荐答案

METROmilwaukee;

Hi METROmilwaukee;

如果可以将标签名称和文本框文本值放入实现IEnumerable的对象就像我在使用Dictionary的代码片段中完成的那样,然后你可以遍历集合并构建XML。

If you can get the tag names and the text box text values into an object that implements IEnumerable like I have done in the code snippet using a Dictionary then you can iterate over the collection and build the XML.


// Using the text box name as the key and the text box text property as the value.
Dictionary<string, string> textBoxes = 
  new Dictionary<string, string>()
  {
     {ItemTitleTextBox.Name, ItemTitleTextBox.Text},  
     {ItemLinkTextBox.Name, ItemLinkTextBox.Text}
  };

var tbElements =
  new XElement( "TextBoxElements",
    from tb in textBoxes
    where !String.IsNullOrEmpty(tb.Value)
    // Using Regex to get the tag name from the TextBox property name 
    let tag = System.Text.RegularExpressions.Regex.Match(tb.Key, "Item(.*)TextBox").Groups[1].Value
    select (new XElement( tag, tb.Value)));

Console.WriteLine(tbElements.ToString());

// The output from Console.WriteLine
<TextBoxElements>         
 <Title>This is the title</Title>
 <Link>This is the link</Link>  
</TextBoxElements>        


这篇关于XElement对象上的条件逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆