当前位置:编程学习 > C#/ASP.NET >>

c# 如何实现js的outerHtml功能(过客进)

比如一段字符串(即是一个网页解析输出后的html代码)
<html>
<head>

</head>
<body>
<table class="ptable">
xxx
</ptable>
</body>

得到结果
<table class="ptable">xxx</ptable>


写一个函数
private string GetHtmlById(string InputHtml,string ClassId)
{
  
 //这里面如何用正则或者其它方法,根据ClassId得到这一个ClassId的outerHtml?

} --------------------编程问答--------------------
Regex reg=new Regex("(?is)<body[^>]*>(?<body>.*?)</body>");
string result=reg.Match("").Groups["body"].Value;
--------------------编程问答--------------------
引用 1 楼 wuyq11 的回复:
Regex reg=new Regex("(?is)<body[^>]*>(?<body>.*?)</body>");
string result=reg.Match("").Groups["body"].Value;


body里面还有其它很多内容的啊。。。。 --------------------编程问答-------------------- 继续等 --------------------编程问答-------------------- http://topic.csdn.net/u/20081009/09/f199eede-a9ed-4d75-858b-29e4e26d63aa.html
--------------------编程问答-------------------- xml + xpath

string html= 
"<html>"+
"<head>"+
"</head>"+
"<body>"+
"<table class=\"ptable\">"+
"xxx"+
"</table>"+
"</body>"+
"</html>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(html);
            XmlNode node = doc.SelectSingleNode("//table[@class='ptable']");
            Console.WriteLine(node.OuterXml);
--------------------编程问答-------------------- outerHtml那样的不好做。你希望这个功能有多严格?html中有自结束标签,还有可能有些标签没有结束标签。如果你只是提取固定格式的内容,那就很好办 --------------------编程问答-------------------- 如果是不限制table,则可以这样比较通用。

        public static void Test()
        {
            string html = @"<html>
<head>

</head>
<body>
<table class=""ptable"">
xxx
</table>
</body>

";
            Console.WriteLine(GetHtmlById(html,"ptable"));          
        }

        public static string GetHtmlById(string InputHtml, string ClassId)
        {
            return Regex.Match(InputHtml, @"(?is)<(\w+)[^<>]*?class=""" + ClassId + @"""[^<>]*>((?<o><\1)|(?<-o></\1)|((?!</(\1)?).)*)*(?(o)(?!))</\1[^>]*>").Value;
        }
--------------------编程问答-------------------- 如果是特定的,只处理table。
public static string GetHtmlById(string InputHtml, string ClassId)
{
    //return Regex.Match(InputHtml, @"(?is)<(\w+)[^<>]*?class=""" + ClassId + @"""[^<>]*>((?<o><\1)|(?<-o></\1)|((?!</(\1)?).)*)*(?(o)(?!))</\1[^>]*>").Value;
    return Regex.Match(InputHtml, @"(?is)<table[^<>]*?class=""" + ClassId + @"""[^<>]*>((?<o><table)|(?<-o></table)|((?!</table?).)*)*(?(o)(?!))</table[^>]*>");
}
--------------------编程问答-------------------- 你范例写错了把<table配对的应该是</table,你是笔误?还是就要这么配对的?
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,