我有以下代码。假设用户可以插入1-4个关键字并单击搜索按钮,如果子标记<item></item>
中的内容包含一个/多个关键字,则会在richtextbox中显示整个<description</description>
的结果进入。但代码不在此行if (itemDescription.Contains(txtComKeyword1 | txtComKeyword2 | txtComKeyword3 | txtComKeyword4)
。
请你们看一下吗?非常感谢您的帮助!谢谢。
以下是我的XML文件结构的一部分:
<item>
<title>[PhoTosynthesIs] Being driven</title>
<author>PhoTosynthesIs</author>
<description>purely by profit, I've decided to stick to my strategy and exit both tranches at 177. Will pick this stock up again when it breaches and holds the next pivot point. gl all</description>
<link>http://www.lse.co.uk/shareChat.asp?ShareTicker=BARC&post=5660817</link>
<pubDate>Wed, 08 Aug 2012 11:43:17 GMT</pubDate>
</item>
<item>
<title>[b36m] alw51</title>
<author>b36m</author>
<description>Could you share your thoughts/opinions on a buy in price based on TW with me please many thanks</description>
<link>http://www.lse.co.uk/shareChat.asp?ShareTicker=BARC&post=5660636</link>
<pubDate>Wed, 08 Aug 2012 11:16:56 GMT</pubDate>
</item>
以下是此功能的代码:
private void searchComByKeywords()
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
try
{
XmlDocument xmlDoc = new XmlDocument(); //* create an xml document object.
string docPath = fileName;
xmlDoc.Load(docPath); //* load the XML document from the specified file.
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("item");
foreach (XmlNode node in nodeList)
{
XmlElement itemElement = (XmlElement)node;
string itemDescription = itemElement.GetElementsByTagName("description")[0].InnerText;
if (itemDescription.Contains(txtComKeyword1 | txtComKeyword2 | txtComKeyword3 | txtComKeyword4)
{
string itemTitle = itemElement.GetElementsByTagName("title")[0].InnerText;
string itemDate = itemElement.GetElementsByTagName("pubDate")[0].InnerText;
string itemAuthor = itemElement.GetElementsByTagName("author")[0].InnerText;
richComResults.AppendText("Author: " + itemAuthor + "\nDate: " + itemDate + "\nTitle: " + itemTitle + "\nDescription: " + itemDescription + "\n\n--------\n\n");
}
//else
//{
// richComResults.AppendText("There is no author " + txtComAuthor.Text.ToString().ToLower() + ". Please ensure you are using a correct author name.");
//}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
答案 0 :(得分:1)
也许你可以试试:
if (itemDescription.Contains(txtComKeyword1) || itemDescription.Contains(txtComKeyword2) || itemDescription.Contains(txtComKeyword3) || itemDescription.Contains(txtComKeyword4))
{
...
}
答案 1 :(得分:0)
当if
语句中的条件复杂且其含义不明确时,我倾向于将其重构为单独的方法。在您的情况下,它可能如下所示:
private static bool DoesItemDescriptionContainOneOf(string description, params string[] items)
{
return items.Any(description.Contains);
}
然后,您的情况将如下所示:
if (DoesItemDescriptionContainOneOf(itemDescription, txtComKeyword1, txtComKeyword2, txtComKeyword3, txtComKeyword4))
{
....
}
很整洁,嗯?