2013-01-07 31 views
0

加入对象(HTML集合)内部字符串的最佳方法?使用Microsoft Studio 2008中,NET 3.5,与HTMLagilityPack对象内部加入字符串的最佳方法

这里的HTML

<div class="content"> 
<ul> 
    <li>Text that I want to scrape </li> 
    <li>Text that I want to scrape </li> 
    <li>Text that I want to scrape </li> 
</ul> 
</div> 

,在这里我的代码

var productfeature = 
    document.DocumentNode.SelectNodes("//div[@class='content']/ul/li"); 

if (productfeature != null) 
{ 
    StringBuilder sb = new StringBuilder(); 
    foreach (HtmlNode node in productfeature) 
    { 
     //Make sure nothing {} inside title 
     string safeint = node.InnerText.Replace("}", "").Replace("{",""); 
     sb.Append(safeint + "}"); //adding } for marking 
    } 
} 

有些文章在这里 我说,它能够更好利用的string.join,buat我不知道如何与对象元素这样

NB:我想要的东西快ER和光..

+1

使用实现'string.Join'将可能导致更清晰,更短的代码,但引擎盖下不应该进行明显的不同。 – Servy

+5

在访问DOM的上下文中使用时,“更快更轻”是相当无意义的术语。这并不快,当然也不轻。避免无谓的优化。 –

+0

以上两条评论都是正确的,但这会帮助你 http://stackoverflow.com/questions/585860/string-join-vs-stringbuilder-which-is-faster – prospector

回答

1

下面是使用string.Join

string delimiter = safeint + "}"; 
string result = "{" + string.Join(delimiter, 
    productfeature.Select(node => removeBraces(node.InnerText)).ToArray()) + "}"; 

public static string removeBraces(string value) 
{ 
    return value.Replace("}", "").Replace("{", ""); 
} 
+0

我有这么多的错误,并且这是'string delimiter = safeint +“}”; string result =“{”+ string.Join(delimiter, productfeature.Select(node => removeBraces(node.InnerText)))+“}”;'inside foreach? – radiaku

+0

@radiaku不,它代替了'foreach'。辅助方法显然需要去其他地方。噢,我忘了.NET 3.5你需要一个额外的'ToArray'。 – Servy

+0

谢谢你,我知道它没有让我的代码比以前更快,但我学到了一些关于string.join和对象的新东西 标记为答案 – radiaku

相关问题