Html को सादे पाठ में कैसे बदलें?


98

मेरे पास एक टेबल में संग्रहीत एचटीएमएल के स्निपेट हैं। पूरे पृष्ठ नहीं, कोई टैग या लाइक नहीं, बस मूल स्वरूपण।

मैं उस एचटीएमएल को केवल पाठ के रूप में प्रदर्शित करने में सक्षम होना चाहता हूं, कोई प्रारूपण नहीं , किसी भी पृष्ठ पर , (वास्तव में सिर्फ पहले 30 - 50 अक्षर लेकिन यह आसान बिट है)।

मैं उस पाठ में "पाठ" को सीधे पाठ के रूप में एक स्ट्रिंग में कैसे रखूं?

तो कोड का यह टुकड़ा।

<b>Hello World.</b><br/><p><i>Is there anyone out there?</i><p>

हो जाता है:

नमस्ते दुनिया। क्या कोई वहां है?


आप SgmlReader का उपयोग करना चाह सकते हैं। code.msdn.microsoft.com/SgmlReader
लियोनार्डो हरेरा

HTML को blackbeltcoder.com/Articles/strings/convert-html-to-text पर सादे पाठ में बदलने के लिए कुछ बहुत ही सरल और सीधे-सरल कोड हैं ।
जोनाथन वुड

यह सही उत्तर था कि मुझे क्या चाहिए - धन्यवाद!
Shaul Behr

W3C के कुछ अच्छे सुझाव यहां दिए गए हैं: w3.org/Tools/html2things.html
रिच

4
एक प्रश्न को एक प्रश्न के डुप्लिकेट के रूप में कैसे चिह्नित किया जा सकता है जो 6 महीने बाद पूछा गया था? थोड़ा पिछड़ा हुआ लगता है ...
स्टुअर्ट हेलविग

जवाबों:


27

यदि आप टैग स्ट्रिपिंग के बारे में बात कर रहे हैं, तो यह अपेक्षाकृत सीधा है अगर आपको <script>टैग जैसी चीजों के बारे में चिंता करने की आवश्यकता नहीं है । यदि आपको केवल इतना करना है कि पाठ को उन टैगों के बिना प्रदर्शित करें जिन्हें आप एक नियमित अभिव्यक्ति के साथ पूरा कर सकते हैं:

<[^>]*>

अगर आपको चिंता करनी है <script> टैग और इस तरह की , तो आपको कुछ अधिक शक्तिशाली और नियमित अभिव्यक्ति की आवश्यकता होगी, क्योंकि आपको राज्य को ट्रैक करने की आवश्यकता है, एक संदर्भ मुक्त व्याकरण (सीएफजी) की तरह। सोचा कि आप इसे 'लेफ्ट टू राइट' या गैर-लालची मिलान के साथ पूरा करने में सक्षम हो सकते हैं।

यदि आप नियमित अभिव्यक्ति का उपयोग कर सकते हैं तो अच्छी जानकारी के साथ कई वेब पेज हैं:

यदि आपको सीएफजी के अधिक जटिल व्यवहार की आवश्यकता है तो मैं तीसरे पक्ष के उपकरण का उपयोग करने का सुझाव दूंगा, दुर्भाग्य से मुझे अनुशंसा करने के लिए अच्छा नहीं पता है।


3
आपको एक्सएमएल में विशेषता मूल्यों, टिप्पणियों, पीआई / सीडीएटी और विरासत एचटीएमएल में विभिन्न सामान्य विकृतियों के बारे में भी चिंता करनी होगी। सामान्य तौर पर [X] [HT] एमएल regexps के साथ पार्स करने के लिए उत्तरदायी नहीं है।
12

11
यह यह करने के लिए एक भयानक तरीका है। सही तरीका यह है कि एचटीएमएल को एक परिवाद के साथ पार्स करें और डोम को केवल श्वेतसूची में प्रस्तुत करने के लिए पार करें।
usr

2
@usr: आप जिस हिस्से का जिक्र कर रहे हैं, वह उत्तर का सीएफजी हिस्सा है। रेगेक्स का उपयोग त्वरित और गंदे टैग स्ट्रिपिंग के लिए किया जा सकता है, इसकी कमजोरियां हैं लेकिन यह त्वरित है और यह आसान है। अधिक जटिल पार्सिंग के लिए सीएफजी आधारित टूल का उपयोग करें (आपके प्रतिमान में एक ऐसा एफएबी जो डोम उत्पन्न करता है)। मैंने परीक्षण नहीं किया है, लेकिन मैं चाहता हूं कि DOM पार्सिंग regex स्ट्रिपिंग की तुलना में धीमी है, अगर प्रदर्शन पर विचार किया जाना चाहिए।
vfilby

1
@vfilby, पहला हमला जो मन में आता है वह लिख रहा है "<div id = \" "(c # string syntax)। गुम एंड कोट्स और मिसिंग क्लोज़िंग ब्रेस पर ध्यान दें। मुझे लगता है कि यह ब्राउज़र को भ्रमित करेगा और टैग संरचना को असंतुलित कर देगा। आप इस हमले के बारे में सोचते हैं? क्या आपको यकीन है कि यह कभी काम नहीं करेगा? बुरा।
usr

1
@vfilby, इससे कोई फर्क नहीं पड़ता कि पार्सिंग लिब भ्रमित है या नहीं। आपको केवल इसे (किसी भी डोम पर) डोम से लेना है और आउटपुट केवल श्वेतसूची में लेना है। यह हमेशा सुरक्षित होता है, इससे कोई फर्क नहीं पड़ता कि पार्स किया गया डोम कैसा दिखता है। साथ ही, मैंने आपको कई उदाहरण बताए हैं जहाँ आपकी "सरल" विधि टैग हटाने में विफल रहेगी।
usr

95

मुक्त और खुला स्रोत HtmlAgilityPack में इसका एक नमूना एक विधि है जो HTML से सादे पाठ में परिवर्तित होता है।

var plainText = HtmlUtilities.ConvertToPlainText(string html);

इसे HTML स्ट्रिंग की तरह फ़ीड करें

<b>hello, <i>world!</i></b>

और आपको एक सादा पाठ परिणाम मिलेगा:

hello world!

10
मैंने पहले HtmlAgilityPack का उपयोग किया है लेकिन मैं ConvertToPlainText का कोई संदर्भ नहीं देख सकता। क्या आप मुझे बता सकते हैं कि मैं इसे कहां पा सकता हूं?
क्षितिज

8
Horatio, यह HtmlAgilityPack के साथ आने वाले नमूनों में से एक में शामिल है: htmlagilitypack.codeplex.com/sourcecontrol/changeset/view/…
यहूदा गेब्रियल हिमांगो

5
दरअसल, एगिलिटी पैक में इसके लिए बिल्ट इन मेथड नहीं है। आप जो जुड़ा हुआ है वह एक उदाहरण है जो नोड पेड़ को हटाने, टैग को हटाने scriptऔर styleआउटपुट स्ट्रिंग में अन्य तत्वों के आंतरिक पाठ को लिखने के लिए चपलता पैक का उपयोग करता है । मुझे संदेह है कि यह वास्तविक दुनिया के इनपुट के साथ बहुत परीक्षण कर चुका है।
लू

3
क्या कोई कृपया उस कोड को प्रदान कर सकता है, जो नमूनों के लिंक के विपरीत है, जिसे ठीक से काम करने के लिए रेट्रोफिट करने की आवश्यकता है?
एरिक के

5
नमूना अब यहां पाया जा सकता है: github.com/ceee/ReadSharp/blob/master/ReadSharp/…
StuartQ

51

मैं HtmlAgilityPack का उपयोग नहीं कर सका, इसलिए मैंने अपने लिए दूसरा सबसे अच्छा समाधान लिखा

private static string HtmlToPlainText(string html)
{
    const string tagWhiteSpace = @"(>|$)(\W|\n|\r)+<";//matches one or more (white space or line breaks) between '>' and '<'
    const string stripFormatting = @"<[^>]*(>|$)";//match any character between '<' and '>', even when end tag is missing
    const string lineBreak = @"<(br|BR)\s{0,1}\/{0,1}>";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />
    var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
    var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
    var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);

    var text = html;
    //Decode html specific characters
    text = System.Net.WebUtility.HtmlDecode(text); 
    //Remove tag whitespace/line breaks
    text = tagWhiteSpaceRegex.Replace(text, "><");
    //Replace <br /> with line breaks
    text = lineBreakRegex.Replace(text, Environment.NewLine);
    //Strip formatting
    text = stripFormattingRegex.Replace(text, string.Empty);

    return text;
}

2
& LT; blabla & gt; बाहर निकाल दिया गया था, इसलिए मैंने पाठ = System.Net.WebUtility.tmlDecode (पाठ) स्थानांतरित कर दिया; विधि के नीचे करने के लिए
Luuk

1
यह बहुत अच्छा था, मैंने एक मल्टीस्पेश कंडेनसर भी जोड़ा क्योंकि html एक सीएमएस से उत्पन्न हो सकता था: var spaceRegex = new Regex ("[] {2,}", RegexOptions.None);
एनकोड

कभी-कभी, html कोड में कोडर की नई लाइन (नई लाइन को टिप्पणी में नहीं देखा जा सकता है, इसलिए मैं इसे [नई लाइन] के साथ दिखाता हूं, जैसे: <br> मैं [नई लाइन] मिस [नई लाइन] आप <br >, तो यह दिखाने के लिए लगता है: "आई मिस यू", लेकिन यह दिखाती है कि मैं [नई लाइन] मिस [नई लाइन] आप। यह सादे पाठ को दर्दनाक बना देता है। क्या आप जानते हैं कि कैसे ठीक किया जाए?
123

@ 123iamking आप इसे रिटर्न टेक्स्ट से पहले उपयोग कर सकते हैं; : text.Replace ("[नई पंक्ति]", "\ n");
असलम बदावी

मैं इसका उपयोग कर रहा था और महसूस किया कि कभी-कभी यह तार की शुरुआत में '>' छोड़ देता है। Regex लगाने का दूसरा उपाय <[^>] *> ठीक काम करता है।
एटिएन चेरलैंड

20

HTTPUtility.HTMLEncode()स्ट्रिंग के रूप में HTML टैग एन्कोडिंग को संभालने के लिए है। यह आपके लिए सभी भारी उठाने का ख्याल रखता है। से MSDN प्रलेखन :

यदि रिक्त स्थान और विराम चिह्न जैसे वर्णों को HTTP स्ट्रीम में पास किया जाता है, तो उन्हें प्राप्त अंत में गलत समझा जा सकता है। HTML एन्कोडिंग उन वर्णों को रूपांतरित करता है जो HTML में चरित्र-इकाई समकक्षों में अनुमत नहीं हैं; HTML डिकोडिंग एन्कोडिंग को उलट देती है। उदाहरण के लिए, जब पाठ के एक ब्लॉक में एम्बेड किया जाता है, वर्ण <और >, HTTP ट्रांसमिशन के रूप में &lt;और इनकोडिंग &gt;

HTTPUtility.HTMLEncode()विधि, यहाँ विस्तृत :

public static void HtmlEncode(
  string s,
  TextWriter output
)

उपयोग:

String TestString = "This is a <Test String>.";
StringWriter writer = new StringWriter();
Server.HtmlEncode(TestString, writer);
String EncodedString = writer.ToString();

वास्तव में एक अच्छा जवाब जॉर्ज धन्यवाद, इसने यह भी उजागर किया कि मैंने पहली बार प्रश्न को कितना खराब तरीके से पूछा। माफ़ करना।
स्टुअर्ट हेलविग

html चपलता पैक दिनांकित है और html5 का समर्थन नहीं कर रहा है
abzarak

10

Vfilby के उत्तर में जोड़ने के लिए, आप अपने कोड के भीतर एक RegEx प्रतिस्थापन कर सकते हैं; कोई नई कक्षाएं आवश्यक नहीं हैं। इस मामले में खुद जैसे अन्य नए लोग इस सवाल पर अड़ गए हैं।

using System.Text.RegularExpressions;

फिर...

private string StripHtml(string source)
{
        string output;

        //get rid of HTML tags
        output = Regex.Replace(source, "<[^>]*>", string.Empty);

        //get rid of multiple blank lines
        output = Regex.Replace(output, @"^\s*$\n", string.Empty, RegexOptions.Multiline);

        return output;
}

19
अच्छा नही! यह समापन कोण कोष्ठक को छोड़ कर स्क्रिप्ट को नियंत्रित करने के लिए छल किया जा सकता है। दोस्तों, कभी ब्लैकलिस्टिंग मत करो। आप ब्लैक लिस्ट करके इनपुट को सैनिटाइज़ नहीं कर सकते । यह तो गलत है।
यूएसआर

7

HTML को सादा पाठ में बदलने के लिए तीन चरण प्रक्रिया

सबसे पहले आपको HtmlAgilityPack Second के लिए Nuget पैकेज स्थापित करने की आवश्यकता है

public class HtmlToText
{
    public HtmlToText()
    {
    }

    public string Convert(string path)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.Load(path);

        StringWriter sw = new StringWriter();
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }

    public string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);

        StringWriter sw = new StringWriter();
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }

    private void ConvertContentTo(HtmlNode node, TextWriter outText)
    {
        foreach(HtmlNode subnode in node.ChildNodes)
        {
            ConvertTo(subnode, outText);
        }
    }

    public void ConvertTo(HtmlNode node, TextWriter outText)
    {
        string html;
        switch(node.NodeType)
        {
            case HtmlNodeType.Comment:
                // don't output comments
                break;

            case HtmlNodeType.Document:
                ConvertContentTo(node, outText);
                break;

            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                    break;

                // get text
                html = ((HtmlTextNode)node).Text;

                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                    break;

                // check the text is meaningful and not a bunch of whitespaces
                if (html.Trim().Length > 0)
                {
                    outText.Write(HtmlEntity.DeEntitize(html));
                }
                break;

            case HtmlNodeType.Element:
                switch(node.Name)
                {
                    case "p":
                        // treat paragraphs as crlf
                        outText.Write("\r\n");
                        break;
                }

                if (node.HasChildNodes)
                {
                    ConvertContentTo(node, outText);
                }
                break;
        }
    }
}

यहूदा हिमांगो के जवाब के संदर्भ में उपरोक्त वर्ग का उपयोग करके

तीसरा आपको ConvertHtml(HTMLContent)एचटीएमएल को प्लेन टेक्स्ट में बदलने के लिए उपरोक्त वर्ग और उपयोग विधि का उद्देश्य बनाने की आवश्यकता हैConvertToPlainText(string html);

HtmlToText htt=new HtmlToText();
var plainText = htt.ConvertHtml(HTMLContent);

क्या मैं HTML में लिंक बदलना छोड़ सकता हूँ? मुझे पाठ में कनवर्ट करते समय html में लिंक रखने की आवश्यकता है?
coder771

6

यह सीमा है कि लंबी इनलाइन व्हाट्सएप को ध्वस्त नहीं करता है, लेकिन यह निश्चित रूप से पोर्टेबल है और वेबब्रोसर जैसे लेआउट का सम्मान करता है।

static string HtmlToPlainText(string html) {
  string buf;
  string block = "address|article|aside|blockquote|canvas|dd|div|dl|dt|" +
    "fieldset|figcaption|figure|footer|form|h\\d|header|hr|li|main|nav|" +
    "noscript|ol|output|p|pre|section|table|tfoot|ul|video";

  string patNestedBlock = $"(\\s*?</?({block})[^>]*?>)+\\s*";
  buf = Regex.Replace(html, patNestedBlock, "\n", RegexOptions.IgnoreCase);

  // Replace br tag to newline.
  buf = Regex.Replace(buf, @"<(br)[^>]*>", "\n", RegexOptions.IgnoreCase);

  // (Optional) remove styles and scripts.
  buf = Regex.Replace(buf, @"<(script|style)[^>]*?>.*?</\1>", "", RegexOptions.Singleline);

  // Remove all tags.
  buf = Regex.Replace(buf, @"<[^>]*(>|$)", "", RegexOptions.Multiline);

  // Replace HTML entities.
  buf = WebUtility.HtmlDecode(buf);
  return buf;
}

4

HtmlAgilityPack में 'ConvertToPlainText' नाम की कोई विधि नहीं है, लेकिन आप एक HTML स्ट्रिंग को CLEAR स्ट्रिंग में बदल सकते हैं:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlString);
var textString = doc.DocumentNode.InnerText;
Regex.Replace(textString , @"<(.|n)*?>", string.Empty).Replace("&nbsp", "");

Thats मेरे लिए काम करता है। लेकिन मैं 'HtmlAgilityPack' में NAME 'ConvertToPlainText' के साथ एक धातु नहीं बना सकता।


3

मुझे लगता है कि 'स्ट्रिंग' एक्सटेंशन विधि बनाने के लिए सबसे आसान तरीका है (रिचर्ड ने जो सुझाव दिया है, उसके आधार पर):

using System;
using System.Text.RegularExpressions;

public static class StringHelpers
{
    public static string StripHTML(this string HTMLText)
        {
            var reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
            return reg.Replace(HTMLText, "");
        }
}

तो बस अपने कार्यक्रम में किसी भी 'स्ट्रिंग' चर पर इस विस्तार विधि का उपयोग करें:

var yourHtmlString = "<div class=\"someclass\"><h2>yourHtmlText</h2></span>";
var yourTextString = yourHtmlString.StripHTML();

मैं इस एक्सटेंशन मेथड का उपयोग html फॉर्मेटेड टिप्पणियों को सादे पाठ में बदलने के लिए करता हूं ताकि यह क्रिस्टल रिपोर्ट पर सही ढंग से प्रदर्शित हो, और यह सही काम करे!


3

मैंने पाया सबसे सरल तरीका:

HtmlFilter.ConvertToPlainText(html);

HtmlFilter वर्ग Microsoft.TeamFoundation.WorkItemTracking.Control.dll में स्थित है

Dll इस तरह फ़ोल्डर में पाया जा सकता है:% ProgramFiles% \ Common Files \ microsoft साझा \ Team Foundation Server \ 14.0 \

VS 2015 में, dll को Microsoft.TeamFoundation.WorkItemTracking.Common.dll के संदर्भ की भी आवश्यकता होती है।


क्या यह स्क्रिप्ट टैग का ध्यान रखता है और क्या यह बोल्ड इटैलिक आदि के रूप में प्रारूपित करता है?
समरा

HTML को सादे पाठ में परिवर्तित करने के लिए एक टीम फाउंडेशन निर्भरता का परिचय, बहुत ही संदिग्ध ...
ViRuSTriNiTy

2

यदि आपके पास HTML टैग्स वाले डेटा हैं और आप इसे प्रदर्शित करना चाहते हैं ताकि कोई व्यक्ति टैग को देख सके, तो HttpServerUtility :: HtmlEncode का उपयोग करें।

यदि आपके पास ऐसा डेटा है जिसमें HTML टैग्स हैं और आप चाहते हैं कि उपयोगकर्ता प्रदान किए गए टैगों को देखें, तो पाठ को उसी तरह प्रदर्शित करें। यदि पाठ संपूर्ण वेब पेज का प्रतिनिधित्व करता है, तो इसके लिए IFRAME का उपयोग करें।

यदि आपके पास ऐसा डेटा है जिसमें HTML टैग्स हैं और आप टैग्स को अलग करना चाहते हैं और सिर्फ अनफ़्लैट किए गए टेक्स्ट को प्रदर्शित करते हैं, तो एक नियमित अभिव्यक्ति का उपयोग करें।


php में एक फंक्शन होता है जिसे स्ट्रिपटेग्स () कहा जाता है, हो सकता है कि आपके पास भी कुछ ऐसा ही हो
mark

"एक नियमित अभिव्यक्ति का उपयोग करें" नहीं! यह ब्लैकलिस्टिंग होगा। आप केवल सफेदी कर सुरक्षित रह सकते हैं। उदाहरण के लिए, आपने याद किया है कि स्टाइल एटिब्यूट में "पृष्ठभूमि: url ('जावास्क्रिप्ट' ... ... ') हो सकता है?" बिल्कुल नहीं, मैं भी नहीं होता। यही कारण है कि ब्लैकलिस्टिंग काम नहीं करती है।
usr

2

मैंने इसी तरह की समस्या का सामना किया है और सबसे अच्छा समाधान पाया है। नीचे कोड मेरे लिए एकदम सही काम करता है।

  private string ConvertHtml_Totext(string source)
    {
     try
      {
      string result;

    // Remove HTML Development formatting
    // Replace line breaks with space
    // because browsers inserts space
    result = source.Replace("\r", " ");
    // Replace line breaks with space
    // because browsers inserts space
    result = result.Replace("\n", " ");
    // Remove step-formatting
    result = result.Replace("\t", string.Empty);
    // Remove repeating spaces because browsers ignore them
    result = System.Text.RegularExpressions.Regex.Replace(result,
                                                          @"( )+", " ");

    // Remove the header (prepare first by clearing attributes)
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*head([^>])*>","<head>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"(<( )*(/)( )*head( )*>)","</head>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(<head>).*(</head>)",string.Empty,
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // remove all scripts (prepare first by clearing attributes)
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*script([^>])*>","<script>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"(<( )*(/)( )*script( )*>)","</script>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    //result = System.Text.RegularExpressions.Regex.Replace(result,
    //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
    //         string.Empty,
    //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"(<script>).*(</script>)",string.Empty,
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // remove all styles (prepare first by clearing attributes)
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*style([^>])*>","<style>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"(<( )*(/)( )*style( )*>)","</style>",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(<style>).*(</style>)",string.Empty,
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // insert tabs in spaces of <td> tags
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*td([^>])*>","\t",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // insert line breaks in places of <BR> and <LI> tags
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*br( )*>","\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*li( )*>","\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // insert line paragraphs (double line breaks) in place
    // if <P>, <DIV> and <TR> tags
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*div([^>])*>","\r\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*tr([^>])*>","\r\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<( )*p([^>])*>","\r\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // Remove remaining tags like <a>, links, images,
    // comments etc - anything that's enclosed inside < >
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"<[^>]*>",string.Empty,
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // replace special characters:
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @" "," ",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&bull;"," * ",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&lsaquo;","<",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&rsaquo;",">",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&trade;","(tm)",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&frasl;","/",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&lt;","<",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&gt;",">",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&copy;","(c)",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&reg;","(r)",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    // Remove all others. More can be added, see
    // http://hotwired.lycos.com/webmonkey/reference/special_characters/
    result = System.Text.RegularExpressions.Regex.Replace(result,
             @"&(.{2,6});", string.Empty,
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // for testing
    //System.Text.RegularExpressions.Regex.Replace(result,
    //       this.txtRegex.Text,string.Empty,
    //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    // make line breaking consistent
    result = result.Replace("\n", "\r");

    // Remove extra line breaks and tabs:
    // replace over 2 breaks with 2 and over 4 tabs with 4.
    // Prepare first to remove any whitespaces in between
    // the escaped characters and remove redundant tabs in between line breaks
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\r)( )+(\r)","\r\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\t)( )+(\t)","\t\t",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\t)( )+(\r)","\t\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\r)( )+(\t)","\r\t",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    // Remove redundant tabs
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\r)(\t)+(\r)","\r\r",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    // Remove multiple tabs following a line break with just one tab
    result = System.Text.RegularExpressions.Regex.Replace(result,
             "(\r)(\t)+","\r\t",
             System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    // Initial replacement target string for line breaks
    string breaks = "\r\r\r";
    // Initial replacement target string for tabs
    string tabs = "\t\t\t\t\t";
    for (int index=0; index<result.Length; index++)
    {
        result = result.Replace(breaks, "\r\r");
        result = result.Replace(tabs, "\t\t\t\t");
        breaks = breaks + "\r";
        tabs = tabs + "\t";
    }

    // That's it.
    return result;
}
catch
{
    MessageBox.Show("Error");
    return source;
}

}

भागने के पात्र जैसे कि \ n और \ r को पहले हटाना पड़ा क्योंकि वे उम्मीद के मुताबिक काम करना बंद कर देते हैं।

इसके अलावा, टेक्स्ट बॉक्स में रिजल्ट स्ट्रिंग डिस्प्ले को सही तरीके से बनाने के लिए, किसी को टेक्स्ट प्रॉपर्टी को असाइन करने के बजाय टेक्स्ट बॉक्स की लाइन्स प्रॉपर्टी को विभाजित करने और सेट करने की आवश्यकता हो सकती है।

this.txtResult.Lines = StripHTML (this.txtSource.Text) .Split ("\ r" .ToCharArray ());

स्रोत: https://www.codeproject.com/Articles/11902/Convert-HTML-to-Plain-Txt-2


0

निर्भर करता है कि आप "html" से क्या मतलब है। सबसे जटिल मामला पूरा वेब पेज होगा। यह भी सबसे आसान है, क्योंकि आप एक टेक्स्ट-मोड वेब ब्राउज़र का उपयोग कर सकते हैं। पाठ मोड ब्राउज़रों सहित वेब ब्राउज़रों की विकिपीडिया लेख सूची देखें । लिंक्स शायद सबसे अच्छी तरह से जाना जाता है, लेकिन दूसरों में से एक आपकी आवश्यकताओं के लिए बेहतर हो सकता है।


जैसा कि उन्होंने कहा था "मेरे पास एक टेबल में संग्रहीत एचटीएमएल के स्निपेट्स हैं।"
एम

0

यहाँ मेरा समाधान है:

public string StripHTML(string html)
{
    var regex = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
    return System.Web.HttpUtility.HtmlDecode((regex.Replace(html, "")));
}

उदाहरण:

StripHTML("<p class='test' style='color:red;'>Here is my solution:</p>");
// output -> Here is my solution:

0

मेरे पास एक ही सवाल था, बस मेरे HTML में एक सरल पूर्व-ज्ञात लेआउट था, जैसे:

<DIV><P>abc</P><P>def</P></DIV>

इसलिए मैं इस तरह के सरल कोड का उपयोग कर समाप्त हुआ:

string.Join (Environment.NewLine, XDocument.Parse (html).Root.Elements ().Select (el => el.Value))

कौन से आउटपुट:

abc
def

0

एक प्रयोग नहीं लिखा था:

using HtmlAgilityPack;
using System;
using System.IO;
using System.Text.RegularExpressions;

namespace foo {
  //small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs
  public static class HtmlToText {

    public static string Convert(string path) {
      HtmlDocument doc = new HtmlDocument();
      doc.Load(path);
      return ConvertDoc(doc);
    }

    public static string ConvertHtml(string html) {
      HtmlDocument doc = new HtmlDocument();
      doc.LoadHtml(html);
      return ConvertDoc(doc);
    }

    public static string ConvertDoc(HtmlDocument doc) {
      using (StringWriter sw = new StringWriter()) {
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
      }
    }

    internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo) {
      foreach (HtmlNode subnode in node.ChildNodes) {
        ConvertTo(subnode, outText, textInfo);
      }
    }
    public static void ConvertTo(HtmlNode node, TextWriter outText) {
      ConvertTo(node, outText, new PreceedingDomTextInfo(false));
    }
    internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo) {
      string html;
      switch (node.NodeType) {
        case HtmlNodeType.Comment:
          // don't output comments
          break;
        case HtmlNodeType.Document:
          ConvertContentTo(node, outText, textInfo);
          break;
        case HtmlNodeType.Text:
          // script and style must not be output
          string parentName = node.ParentNode.Name;
          if ((parentName == "script") || (parentName == "style")) {
            break;
          }
          // get text
          html = ((HtmlTextNode)node).Text;
          // is it in fact a special closing node output as text?
          if (HtmlNode.IsOverlappedClosingElement(html)) {
            break;
          }
          // check the text is meaningful and not a bunch of whitespaces
          if (html.Length == 0) {
            break;
          }
          if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace) {
            html = html.TrimStart();
            if (html.Length == 0) { break; }
            textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;
          }
          outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @"\s{2,}", " ")));
          if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1])) {
            outText.Write(' ');
          }
          break;
        case HtmlNodeType.Element:
          string endElementString = null;
          bool isInline;
          bool skip = false;
          int listIndex = 0;
          switch (node.Name) {
            case "nav":
              skip = true;
              isInline = false;
              break;
            case "body":
            case "section":
            case "article":
            case "aside":
            case "h1":
            case "h2":
            case "header":
            case "footer":
            case "address":
            case "main":
            case "div":
            case "p": // stylistic - adjust as you tend to use
              if (textInfo.IsFirstTextOfDocWritten) {
                outText.Write("\r\n");
              }
              endElementString = "\r\n";
              isInline = false;
              break;
            case "br":
              outText.Write("\r\n");
              skip = true;
              textInfo.WritePrecedingWhiteSpace = false;
              isInline = true;
              break;
            case "a":
              if (node.Attributes.Contains("href")) {
                string href = node.Attributes["href"].Value.Trim();
                if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase) == -1) {
                  endElementString = "<" + href + ">";
                }
              }
              isInline = true;
              break;
            case "li":
              if (textInfo.ListIndex > 0) {
                outText.Write("\r\n{0}.\t", textInfo.ListIndex++);
              } else {
                outText.Write("\r\n*\t"); //using '*' as bullet char, with tab after, but whatever you want eg "\t->", if utf-8 0x2022
              }
              isInline = false;
              break;
            case "ol":
              listIndex = 1;
              goto case "ul";
            case "ul": //not handling nested lists any differently at this stage - that is getting close to rendering problems
              endElementString = "\r\n";
              isInline = false;
              break;
            case "img": //inline-block in reality
              if (node.Attributes.Contains("alt")) {
                outText.Write('[' + node.Attributes["alt"].Value);
                endElementString = "]";
              }
              if (node.Attributes.Contains("src")) {
                outText.Write('<' + node.Attributes["src"].Value + '>');
              }
              isInline = true;
              break;
            default:
              isInline = true;
              break;
          }
          if (!skip && node.HasChildNodes) {
            ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten) { ListIndex = listIndex });
          }
          if (endElementString != null) {
            outText.Write(endElementString);
          }
          break;
      }
    }
  }
  internal class PreceedingDomTextInfo {
    public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten) {
      IsFirstTextOfDocWritten = isFirstTextOfDocWritten;
    }
    public bool WritePrecedingWhiteSpace { get; set; }
    public bool LastCharWasSpace { get; set; }
    public readonly BoolWrapper IsFirstTextOfDocWritten;
    public int ListIndex { get; set; }
  }
  internal class BoolWrapper {
    public BoolWrapper() { }
    public bool Value { get; set; }
    public static implicit operator bool(BoolWrapper boolWrapper) {
      return boolWrapper.Value;
    }
    public static implicit operator BoolWrapper(bool boolWrapper) {
      return new BoolWrapper { Value = boolWrapper };
    }
  }
}

0

मुझे लगता है कि इसका एक सरल उत्तर है:

public string RemoveHTMLTags(string HTMLCode)
{
    string str=System.Text.RegularExpressions.Regex.Replace(HTMLCode, "<[^>]*>", "");
    return str;
}

0

किसी दिए गए HTML दस्तावेज़ के शाब्दिक संक्षिप्त नाम के लिए ओपी प्रश्न के सटीक समाधान की तलाश करने वाले किसी भी व्यक्ति के लिए, बिना नए अंक और HTML टैग के, कृपया नीचे दिए गए समाधान को खोजें।

हर प्रस्तावित समाधान की तरह, नीचे दिए गए कोड के साथ कुछ धारणाएं हैं:

  • स्क्रिप्ट या स्टाइल टैग में स्क्रिप्ट और शैली टैग शामिल नहीं होने चाहिए
  • अंतरिक्ष के बिना केवल प्रमुख इनलाइन तत्व ही इनलाइन होंगे, अर्थात he<span>ll</span>oआउटपुट होना चाहिए hello। इनलाइन टैग की सूची: https://www.w3schools.com/htmL/html_blocks.asp

उपरोक्त को ध्यान में रखते हुए, संकलित नियमित अभिव्यक्तियों के साथ निम्नलिखित स्ट्रिंग एक्सटेंशन HTML से बच गए वर्णों और नल इनपुट पर शून्य के संबंध में अपेक्षित सादे पाठ का उत्पादन करेगा।

public static class StringExtensions
{
    public static string ConvertToPlain(this string html)
    {
        if (html == null)
        {
            return html;
        }

        html = scriptRegex.Replace(html, string.Empty);
        html = inlineTagRegex.Replace(html, string.Empty);
        html = tagRegex.Replace(html, " ");
        html = HttpUtility.HtmlDecode(html);
        html = multiWhitespaceRegex.Replace(html, " ");

        return html.Trim();
    }

    private static readonly Regex inlineTagRegex = new Regex("<\\/?(a|span|sub|sup|b|i|strong|small|big|em|label|q)[^>]*>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex scriptRegex = new Regex("<(script|style)[^>]*?>.*?</\\1>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex tagRegex = new Regex("<[^>]+>", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex multiWhitespaceRegex = new Regex("\\s+", RegexOptions.Compiled | RegexOptions.Singleline);
}

-4

सार्वजनिक स्थैतिक स्ट्रिंग StripTags2 (स्ट्रिंग html) {वापसी html.Replace ("<", "<")। प्रतिस्थापित करें (">", ">"); }

इसके द्वारा आप एक स्ट्रिंग में सभी "<" और ">" से बच जाते हैं। क्या ये वही है जो तुम चाहते हो?


... आह। खैर अब जवाब (अस्पष्ट प्रश्न की व्याख्या के साथ) पूरी तरह से बदल गया है, मैं & amp की कमी पर निट्स उठाऊंगा; इसके बजाय एन्कोडिंग। ;-)
बॉब

2
मुझे नहीं लगता कि पहिया को सुदृढ़ करना एक अच्छा विचार है - खासकर जब आपका पहिया चौकोर हो। आपको इसके बजाय HTMLEncode का उपयोग करना चाहिए।
क्रामि
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.