Skip to main content
 首页 » 编程设计

c#之从 XHTML 文档中去除特定标签(但保留其内容)的机制

2025年05月04日30虾米哥

我想要一种从 XHTML 文档中去除标签的简单而简单的方法,并且相信在所有选项中必须有一些足够简单的东西,例如:XSLT、XPath、XQuery、使用 .NET XML 命名空间的自定义 C# 编程。我对别人开放。

For example, I want to strip all <b> tags from an XHTML document but keep their inner content and child tags (i.e. not simply skip the bold tag and its children).



我需要维护原始文档的结构减去剥离的标签。

想法:
  • 我看过 XSLT 匹配元素以供选择的能力;但是,我想默认匹配所有内容,但有几个异常(exception),我不确定这是否有利于这一点。这就是我现在正在看的。
  • XQuery 我还没有开始研究。 (XQuery 更新:简要了解了这项技术,它在功能上与 SQL 相当,我看不出它如何维护原始文档的嵌套节点结构——我认为这不是竞争者)。
  • 一个定制 C#/.NET XML 命名空间 程序可能是可行的,因为我已经有了一个想法,但我的直接假设是,与创建这些其他特定于 XML 的匹配语言的原因相比,它可能更复杂。
  • ...另一种使能技术我还没考虑...
  • 请您参考如下方法:

    I need to maintain the structure of the original document minus the stripped tags



    你想过 XSLT 吗?这是专门为转换 XML 和一般树结构而设计的语言。

    本次改造 :
    <xsl:stylesheet version="1.0" 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
     <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> 
     <xsl:strip-space elements="*"/> 
     
     <xsl:template match="node()|@*"> 
      <xsl:copy> 
       <xsl:apply-templates select="node()|@*"/> 
      </xsl:copy> 
     </xsl:template> 
     
     <xsl:template match="b"> 
      <xsl:apply-templates/> 
     </xsl:template> 
    </xsl:stylesheet> 
    

    当应用于任何 XHTML 文档时,如 下面的一个:
    <html> 
     <head/> 
     <body> 
      <p> Hello, <b>World</b>!</p> 
     </body> 
    </html> 
    

    产生想要的正确结果 , 在这种情况下:
    <html> 
       <head/> 
       <body> 
          <p> Hello, World!</p> 
       </body> 
    </html>