分析剪贴板功能 GetData(DataFormat.Html) 输出的标准类

本文关键字:输出 标准 Html DataFormat 剪贴板 功能 GetData | 更新日期: 2023-09-27 17:56:35

对不起标题...

所以我想从剪贴板中提取文本。此文本是从网页(在浏览器中)复制的。就我而言,它是一个包含一些数据的表格。

所以我使用以下代码提取了数据(它以字符串形式出现):

IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Html))
{
    string s = (string)iData.GetData(DataFormats.Html);
}

我从中得到的(s包含的内容)如下:

Version:0.9
StartHTML:0000000397
EndHTML:0000004086
StartFragment:0000000433
EndFragment:0000004050
SourceURL:Bla Bla Bla
<html>
<body>
<!--StartFragment--><table class="listing tickets">Bla Bla Bla</table><!--EndFragment-->
</body>
</html>

所以,再说一遍。是否有任何标准类可以解析此数据,或者我应该自己创建一个?

分析剪贴板功能 GetData(DataFormat.Html) 输出的标准类

好的,所以答案似乎是否定的!这让我有些惊讶...

无论如何。我做了自己的助手类,也许可以帮助你。这只是众多可能的解决方案之一。对于我的应用程序,如果未找到任何内容,则返回 null 效果很好,也许您想要一个例外。还要记住,我将其作为副项目制作,因此没有对代码进行广泛的测试,因此我不保证这有效

public class ClipboardHtmlOutput
{
    public Double Version { get; private set; }
    public String Source { get; private set; }
    public String Input { get; private set; }
    //public String Html { get { return Input.Substring(startHTML, (endHTML - startHTML)); } }
    public String Html { get { return Input.Substring(startHTML, Math.Min(endHTML - startHTML, Input.Length - startHTML)); } }
    public String Fragment { get { return Input.Substring(startFragment, (endFragment - startFragment)); } }
    private int startHTML;
    private int endHTML;
    private int startFragment;
    private int endFragment;
    public static ClipboardHtmlOutput ParseString(string s)
    {
        ClipboardHtmlOutput html = new ClipboardHtmlOutput();
        string pattern = @"Version:(?<version>[0-9]+(?:'.[0-9]*)?).+StartHTML:(?<startH>'d*).+EndHTML:(?<endH>'d*).+StartFragment:(?<startF>'d+).+EndFragment:(?<endF>'d*).+SourceURL:(?<source>f|ht{1}tps?://[-a-zA-Z0-9@:%_'+.~#?&//=]+)";
        Match match = Regex.Match(s, pattern, RegexOptions.Singleline);
        if (match.Success)
        {
            try
            {
                html.Input = s;
                html.Version = Double.Parse(match.Groups["version"].Value, CultureInfo.InvariantCulture);
                html.Source = match.Groups["source"].Value;
                html.startHTML = int.Parse(match.Groups["startH"].Value);
                html.endHTML = int.Parse(match.Groups["endH"].Value);
                html.startFragment = int.Parse(match.Groups["startF"].Value);
                html.endFragment = int.Parse(match.Groups["endF"].Value);
            }
            catch (Exception fe)
            {
                return null;
            }
            return html;
        }
        return null;
    }
}

用法可能是这样的:

IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Html))
{
    ClipboardHtmlOutput cho = ClipboardHtmlOutput.ParseString((string)iData.GetData(DataFormats.Html));
    XmlDocument xml = new XmlDocument();
    xml.LoadXml(cho.Fragment);
}

以下方法是Microsoft的方法。此方法包含在示例"XAML 到 HTML 转换演示"中的类 HtmlParser 中,您可以在此处下载:https://code.msdn.microsoft.com/windowsdesktop/XAML-to-HTML-Conversion-ed25a674/view/SourceCode。

有关"HTML 剪贴板格式"的其他信息,您可以在此处找到:https://msdn.microsoft.com/en-us/library/aa767917(v=vs.85).aspx

/// <summary>
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html data part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
    int startHtmlIndex = htmlDataString.IndexOf("StartHTML:");
    if (startHtmlIndex < 0)
    {
        return "ERROR: Urecognized html header";
    }
    // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
    // which could be wrong assumption. We need to implement more flrxible parsing here
    startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length));
    if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
    {
        return "ERROR: Urecognized html header";
    }
    int endHtmlIndex = htmlDataString.IndexOf("EndHTML:");
    if (endHtmlIndex < 0)
    {
        return "ERROR: Urecognized html header";
    }
    // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
    // which could be wrong assumption. We need to implement more flrxible parsing here
    endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length));
    if (endHtmlIndex > htmlDataString.Length)
    {
        endHtmlIndex = htmlDataString.Length;
    }
    return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}

25.02.2015 新增

在我的实施之后。我必须注意 UTF-8(请参阅方法和方法)

/// <summary>
/// Extracts selected Html fragment string from clipboard data by parsing header information 
/// in htmlDataString
/// </summary>
/// <param name="htmlDataString">
/// String representing Html clipboard data. This includes Html header
/// </param>
/// <returns>
/// String containing only the Html selection part of htmlDataString, without header
/// </returns>
internal static string ExtractHtmlFragmentFromClipboardData(string htmlDataString)
{
    // HTML Clipboard Format
    // (https://msdn.microsoft.com/en-us/library/aa767917(v=vs.85).aspx)
    // The fragment contains valid HTML representing the area the user has selected. This 
    // includes the information required for basic pasting of an HTML fragment, as follows:
    //  - Selected text. 
    //  - Opening tags and attributes of any element that has an end tag within the selected text. 
    //  - End tags that match the included opening tags. 
    // The fragment should be preceded and followed by the HTML comments <!--StartFragment--> and 
    // <!--EndFragment--> (no space allowed between the !-- and the text) to indicate where the 
    // fragment starts and ends. So the start and end of the fragment are indicated by these 
    // comments as well as by the StartFragment and EndFragment byte counts. Though redundant, 
    // this makes it easier to find the start of the fragment (from the byte count) and mark the 
    // position of the fragment directly in the HTML tree.
    // Byte count from the beginning of the clipboard to the start of the fragment.
    int startFragmentIndex = htmlDataString.IndexOf("StartFragment:");
    if (startFragmentIndex < 0)
    {
        return "ERROR: Unrecognized html header";
    }
    // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
    // which could be wrong assumption. We need to implement more flrxible parsing here
    startFragmentIndex = Int32.Parse(htmlDataString.Substring(startFragmentIndex + "StartFragment:".Length, 10));
    if (startFragmentIndex < 0 || startFragmentIndex > htmlDataString.Length)
    {
        return "ERROR: Unrecognized html header";
    }
    // Byte count from the beginning of the clipboard to the end of the fragment.
    int endFragmentIndex = htmlDataString.IndexOf("EndFragment:");
    if (endFragmentIndex < 0)
    {
        return "ERROR: Unrecognized html header";
    }
    // TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
    // which could be wrong assumption. We need to implement more flrxible parsing here
    endFragmentIndex = Int32.Parse(htmlDataString.Substring(endFragmentIndex + "EndFragment:".Length, 10));
    if (endFragmentIndex > htmlDataString.Length)
    {
        endFragmentIndex = htmlDataString.Length;
    }
    // CF_HTML is entirely text format and uses the transformation format UTF-8
    byte[] bytes = Encoding.UTF8.GetBytes(htmlDataString);
    return Encoding.UTF8.GetString(bytes, startFragmentIndex, endFragmentIndex - startFragmentIndex);
}