日期:2014-05-18  浏览次数:20881 次

c# 服务端去解析dom元素,或者xml,或者其它方法实现
比如我有一段字符串
C# code

 <div class="mzc_stepBar" style="float: left; text-align: right; width: 70%;">
                <ul>
                    <li class="mzc_active"><span>1</span></li>
                    <li><span>2</span></li>
                    <li class="mzc_last"><span>3</span></li>
                </ul>
                <div class="mzc_barLeft mzc_active">
                </div>
                <div class="mzc_barRight">
                </div>
            </div>



我在服务端如果想找到属于3的span,用什么方法最合适呢?
有人说可以在服务端用jquery的函数
有人说解析成dom
又有人说正则表达式(实在无奈可以用)


大家有没有真正在服务端实现用dom或者jquery呢?

如果有的话,请附上代码,或者针对性的解决方案。

------解决方案--------------------
正则,或者HtmlAgilityPack
去网上查查吧! 

------解决方案--------------------
用dom最好。
我只能给你复制我自己的代码 
dom写的找不到了。不好意思 , 参考这个吧。
 private void button1_Click(object sender, EventArgs e)
{
string test = Application.StartupPath + "WriteLines.html";
string textResult = Convert(test );
MessageBox.Show(textResult );
}
public static string Convert(string html)
{
if (string.IsNullOrEmpty(html.Trim()))
{
return string.Empty;
}
using (SgmlReader reader = new SgmlReader())
{
reader.DocType = "HTML";
reader.InputStream = new StringReader(html);
using (StringWriter stringWriter = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
{
reader.WhitespaceHandling = WhitespaceHandling.None;
writer.Formatting = Formatting.Indented;
XmlDocument doc = new XmlDocument();
doc.Load(reader);
doc.Save("c:\\txt.xml");
if (doc.DocumentElement == null)
{
return string.Empty;
}
else
{
doc.DocumentElement.WriteContentTo(writer);
}
writer.Close();
string xhtml = stringWriter.ToString();
return xhtml;
}
}
}
}

private void button2_Click(object sender, EventArgs e)
{
object Zero = 0;
object EmptyString = "";
axWebBrowser1.Navigate(textBox1.Text, ref Zero, ref EmptyString, ref EmptyString, ref EmptyString);
}

private void axWebBrowser1_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e)
{
IHTMLDocument2 HTMLDocument = (IHTMLDocument2)axWebBrowser1.Document;
IHTMLElementCollection links = HTMLDocument.links;

listBox1.Items.Clear();
string uspath = Application.StartupPath + "\\WriteLines.html";
uspath.Remove(0);
//using ( StreamWriter sw = new StreamWriter(@"C:\WriteLines.html", true))
using (StreamWriter sw = new StreamWriter(uspath, true))