如何使用 WebView2 控件对本地文件执行 XML / XSL 转换?

How can you perform a XML / XSL transformation for local files with the WebView2 control?

Microsoft Edge(以及 WebView2 控件)允许我们导航到 XML 个文件,这些文件被转换为 HTML 个文件。但当 XML 文件在 PC 本地时,这不起作用。

我很感激我们可以创建一个本地 Web 服务器并使用 localhost,但这需要大量工作。 CHtmlView 控件没有这个问题。


我注意到一个类似的问题 How to use WebView2 to display XML content using XSL transforms? 但它与 WPF 有关。毫无疑问,相同的选项可以用于 WebView2 对象。

我在 WebView2 GitHub 网站上进行了讨论,找到了解决方案。

您需要使用命令行选项 --allow-file-access-from-files,这将允许使用本地 XML 链接。调用 Microsoft Edge 时,您只需在命令行上传递它。但这是使用 WebView2 控件的方式:

void CWebBrowser::InitializeWebView()
{
   CloseWebView();

   CString subFolder = GetInstallPath();
   CString appData = GetUserDataFolder();

   auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
   CHECK_FAILURE(options->put_AdditionalBrowserArguments(L"--allow-file-access-from-files"));

   HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
       subFolder,
       appData,
       options.Get(),
       Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
           this,
           &CWebBrowser::OnCreateEnvironmentCompleted).Get());

   if (!SUCCEEDED(hr))
   {
      CString text;
      if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
      {
         text = L"Cannot found the WebView2 component.";
      }
      else
      {
         text = L"Cannot create the webview environment.";
      }

      ShowFailure(hr, text);
   }
}

上面的代码片段展示了如何使用 CoreWebView2EnvironmentOptions 参数。