日期:2014-05-20  浏览次数:20756 次

使用IMarkupServices解析HTML的问题,是MS的一个BUG吗?
最近查阅到一些关于使用C#   IMarkupServices解析HTML的案例,都是同一篇文件,是使用Microsoft.mshtml这个COM组件解析:

1)建立ConsoleApplication工程,引用Microsoft.mshtml组件,修改项目Build属性,允许使用unsafe代码
2)定义IPersistStreamInit接口

using   System;
using   System.Runtime.InteropServices;

namespace   mshtml
{
  [ComVisible(true),   ComImport(),   Guid( "7FD52380-4E07-101B-AE2D-08002B2EC713 "),   InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  public   interface   IPersistStreamInit
  {
    void   GetClassID([In,   Out]   ref   Guid   pClassID);
    [return:   MarshalAs(UnmanagedType.I4)][PreserveSig]
    int   IsDirty();
    void   Load([In,   MarshalAs(UnmanagedType.Interface)]   UCOMIStream   pstm);
    void   Save([In,   MarshalAs(UnmanagedType.Interface)]   UCOMIStream   pstm,
    [In,   MarshalAs(UnmanagedType.I4)]   int   fClearDirty);
    void   GetSizeMax([Out,   MarshalAs(UnmanagedType.LPArray)]   long   pcbSize);
    void   InitNew();
  }
}

3)编写主体代码

using   System;
using   System.Runtime.InteropServices;
using   mshtml;

namespace   ctest2
{
  class   Class1
  {
    [STAThread]
    static   void   Main(string[]   args)
    {
      IHTMLDocument2   doc   =   Parse( " <B> TEST </B> ");
      //使用doc解析
    }

    public   static   unsafe   IHTMLDocument2     Parse(string   s)
    {
      IHTMLDocument2   pDocument=new   HTMLDocumentClass();      
      if(pDocument!=null)
      {
        IPersistStreamInit   pPersist=pDocument   as   IPersistStreamInit   ;
        pPersist.InitNew();
        IMarkupServices   ms=pDocument   as   IMarkupServices;
        if(ms   !=   null)
        {
          //省略这部份内容,需要的用户请上网查找
        }        
      }
    }
    return   pDocument;
}

问题在这里,同一代码在同一计算机上,在VS2003中编译后运行,语句IMarkupServices   ms=pDocument   as   IMarkupServices返回的ms中正确的,
而且VS2005+SP1中编译后运行,返回的是null值,也就是说没有实现这个接口。

这是怎么回事?google了一下,有几个人也和我有一样的问题(有个人怀疑是线程模式的问题,我认为不对,我的这两个都是Console,模式应该是一样的),但是没有答案,晕死。

------解决方案--------------------
用C++来写吧
------解决方案--------------------
不才. 那篇文章是我写的. 发现了很多IMarkupServices的Bug, 所以自己写了一个HTML DOM Parser了