将HTML转成XHTML并清除一些无用的标签和属性

王朝学院·作者佚名  2016-05-22
窄屏简体版  字體: 小  |  中  |  大  |  超大  

将HTML转成XHTML并清除一些无用的标签和属性介绍这是一个能帮你从HTML生成有效XHTML的经典库。它还提供对标签以及属性过滤的支持。你可以指定允许哪些标签和属性可在出现在输出中,而其他的标签过滤掉。你也可以使用这个库清理Microsoft Word文档转化成HTML时生成的臃肿的HTML。你也在将HTML发布到博客网站前清理一下,否则像WordPRess、b2evolution等博客引擎会拒绝的。

它是如何工作的里面有两个类:HtmlReader和HtmlWriter

HtmlReader拓展了著名的由Chris Clovett开发的SgmlReader。当它读取HTML时,它跳过所有有前缀的节点。其中,所有像<o:p>、<o:Document>、<st1:personname>等上百的无用标签被滤除了。这样你读取的HTML就剩下核心的HTML标签了。

HtmlWriter拓展了常规的xmlWriter,XmlWriter生成XML。XHTML本质上是XML格式的HTML。所有你熟悉使用的标签——比如<img>、<br>和<hr>,都不是闭合的标签——在XHTML中必需是空元素形式,像<img .. />、<br/>和<hr/>。由于XHTML是常见的XML格式,你可以方便的使用XML解析器读取XHTML文档。这使得有了应用XPath搜索的机会。

HtmlReaderHtmlReader很简单,下面是完整的类:

12345678910111213141516171819202122232425262728293031323334

//////Thisclassskipsallnodeswhichhassome///kindofprefix.Thistrickdoesthejob///tocleanupMSWord/OutlookHTMLmarkups.///publicclassHtmlReader:Sgml.SgmlReader{publicHtmlReader(TextReaderreader):base(){base.InputStream=reader;base.DocType="HTML";}publicHtmlReader(stringcontent):base(){base.InputStream=newStringReader(content);base.DocType="HTML";}publicoverrideboolRead(){boolstatus=base.Read();if(status){if(base.NodeType==XmlNodeType.Element){//Gotanodewithprefix.Thismustbeone//ofthose""orsomethingelse.//Skipthisnodeentirely.Wewantprefix//lessnodessothattheresultantXML//requiresnotnamespace.if(base.Name.IndexOf(':')>0)base.Skip();}}returnstatus;}}

HtmlWriter这个类是有点麻烦。下面是使用技巧:

重写WriteString方法并避免使用常规的XML编码。对HTML文件手动更改编码。

重写WriteStartElementis以避免不被允许的标签写到输出中。

重写WriteAttributesis以避免不需求的属性。

让我们分部分来看下整个类:

可配置性你可以通过修改下面的部分配置HtmlWriter:

12345678910111213141516171819202122232425262728

publicclassHtmlWriter:XmlTextWriter{//////Ifsettotrue,itwillfiltertheoutput///byusingtagandattributefiltering,///spacereduceetc///publicboolFilterOutput=false;//////Iftrue,itwillreduceconsecutivewithoneinstance///publicboolReduceConsecutiveSpace=true;//////Setthetagnamesinlowercasewhichareallowedtogotooutput///publicstring[]AllowedTags=newstring[]{"p","b","i","u","em","big","small","div","img","span","blockquote","code","pre","br","hr","ul","ol","li","del","ins","strong","a","font","dd","dt"};//////Ifanytagfoundwhichisnotallowed,itisreplacedbythistag.///Specifyatagwhichhasl

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航