Chuyển đổi HTML sang XHTML JavaScript

Chuyển đổi HTML sang XHTML trong khi áp dụng các bộ lọc thẻ và thuộc tính để tạo ra HTML đẹp và rõ ràng để đăng trên web

  • Tải xuống tệp nguồn - 48. 3KB

Giới thiệu

Đây là thư viện lớp giúp bạn tạo XHTML hợp lệ từ HTML. Nó cũng cung cấp hỗ trợ lọc thẻ và thuộc tính. Bạn có thể chỉ định chính xác những thẻ và thuộc tính nào được cho phép trong đầu ra và các thẻ khác được lọc ra. Bạn có thể sử dụng thư viện này để xóa HTML cồng kềnh mà tài liệu Microsoft Word tạo ra khi chuyển đổi sang HTML. Bạn cũng có thể sử dụng nó để dọn sạch HTML trước khi đăng lên các trang blog để HTML của bạn không bị từ chối bởi các công cụ blog như WordPress, B2evolution, v.v.

Làm thế nào nó hoạt động

Có hai lớp. HtmlReaderHtmlWriter

HtmlReader mở rộng SgmlReader nổi tiếng từ Chris Clovett. Khi đọc HTML, nó sẽ bỏ qua bất kỳ nút nào có tiền tố nào đó. Kết quả là tất cả những thẻ khó chịu như , ,

public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
0 và hàng trăm thẻ khác được lọc ra. Do đó, HTML bạn đọc không có các thẻ không phải là thẻ HTML cốt lõi

HtmlWriter mở rộng

public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
2 thông thường, làm cho nó tạo ra XML. XHTML về cơ bản là HTML ở định dạng XML. Tất cả các thẻ quen thuộc mà bạn sử dụng -- như
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
3,
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
4 và
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
5, không có thẻ đóng -- phải ở định dạng phần tử trống trong XHTML, i. e.
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
6,
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
7 và
public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}
8. Vì XHTML là một tài liệu XML được định dạng tốt, bạn có thể dễ dàng đọc tài liệu XHTML bằng các trình phân tích cú pháp XML. Điều này cho bạn cơ hội để áp dụng tìm kiếm XPath

Trình đọc Html

HtmlReader khá đơn giản. Đây là toàn bộ lớp học

C#

________số 8_______

HtmlWriter

Lớp này phức tạp hơn một chút. Dưới đây là những thủ thuật đã được sử dụng

  • Ghi đè phương thức
    /// 
    /// The reason why we are overriding
    /// this method is, we do not want the output to be
    /// encoded for texts inside attribute
    /// and inside node elements. For example, all the  
    /// gets converted to &nbsp in output. But this does not 
    /// apply to HTML. In HTML, we need to have   as it is.
    /// 
    /// 
    public override void WriteString[string text]
    {
        // Change all non-breaking space to normal space
        text = text.Replace[ " ", " " ];
        /// When you are reading RSS feed and writing Html, 
        /// this line helps remove those CDATA tags
        text = text.Replace[""];
        text = text.Replace["]]>", ""];
    
        // Do some encoding of our own because
        // we are going to use WriteRaw which won't
        // do any of the necessary encoding
        text = text.Replace[ "", ">" ];
        text = text.Replace[ "'", "'" ];
        text = text.Replace[ "\"", ""e;" ];
    
        if[ this.FilterOutput ]
        {
            text = text.Trim[];
    
            // We want to replace consecutive spaces
            // to one space in order to save horizontal width
            if[ this.ReduceConsecutiveSpace ] 
                text = text.Replace["   ", " "];
            if[ this.RemoveNewlines ] 
                text = text.Replace[Environment.NewLine, " "];
    
            base.WriteRaw[ text ];
        }
        else
        {
            base.WriteRaw[ text ];
        }
    }
    0 của
    public class HtmlWriter : XmlTextWriter
    {
        /// 
        /// If set to true, it will filter the output
        /// by using tag and attribute filtering,
        /// space reduce etc
        /// 
        public bool FilterOutput = false;
        /// 
        /// If true, it will reduce consecutive   with one instance
        /// 
        public bool ReduceConsecutiveSpace = true;
        /// 
        /// Set the tag names in lower case which are allowed to go to output
        /// 
        public string [] AllowedTags = 
            new string[] { "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"};
        /// 
        /// If any tag found which is not allowed, it is replaced by this tag.
        /// Specify a tag which has least impact on output
        /// 
        public string ReplacementTag = "dd";
        /// 
        /// New lines \r\n are replaced with space 
        /// which saves space and makes the
        /// output compact
        /// 
        public bool RemoveNewlines = true;
        /// 
        /// Specify which attributes are allowed. 
        /// Any other attribute will be discarded
        /// 
        public string [] AllowedAttributes = new string[] 
        { 
            "class", "href", "target", "border", "src", 
            "align", "width", "height", "color", "size" 
        };
    }
    2 và ngăn nó mã hóa nội dung bằng cách sử dụng mã hóa XML thông thường. Việc mã hóa được thực hiện thủ công cho các tài liệu HTML
  • /// 
    /// The reason why we are overriding
    /// this method is, we do not want the output to be
    /// encoded for texts inside attribute
    /// and inside node elements. For example, all the  
    /// gets converted to &nbsp in output. But this does not 
    /// apply to HTML. In HTML, we need to have   as it is.
    /// 
    /// 
    public override void WriteString[string text]
    {
        // Change all non-breaking space to normal space
        text = text.Replace[ " ", " " ];
        /// When you are reading RSS feed and writing Html, 
        /// this line helps remove those CDATA tags
        text = text.Replace[""];
        text = text.Replace["]]>", ""];
    
        // Do some encoding of our own because
        // we are going to use WriteRaw which won't
        // do any of the necessary encoding
        text = text.Replace[ "", ">" ];
        text = text.Replace[ "'", "'" ];
        text = text.Replace[ "\"", ""e;" ];
    
        if[ this.FilterOutput ]
        {
            text = text.Trim[];
    
            // We want to replace consecutive spaces
            // to one space in order to save horizontal width
            if[ this.ReduceConsecutiveSpace ] 
                text = text.Replace["   ", " "];
            if[ this.RemoveNewlines ] 
                text = text.Replace[Environment.NewLine, " "];
    
            base.WriteRaw[ text ];
        }
        else
        {
            base.WriteRaw[ text ];
        }
    }
    2 được ghi đè để ngăn các thẻ được ghi vào đầu ra không được phép
  • /// 
    /// The reason why we are overriding
    /// this method is, we do not want the output to be
    /// encoded for texts inside attribute
    /// and inside node elements. For example, all the  
    /// gets converted to &nbsp in output. But this does not 
    /// apply to HTML. In HTML, we need to have   as it is.
    /// 
    /// 
    public override void WriteString[string text]
    {
        // Change all non-breaking space to normal space
        text = text.Replace[ " ", " " ];
        /// When you are reading RSS feed and writing Html, 
        /// this line helps remove those CDATA tags
        text = text.Replace[""];
        text = text.Replace["]]>", ""];
    
        // Do some encoding of our own because
        // we are going to use WriteRaw which won't
        // do any of the necessary encoding
        text = text.Replace[ "", ">" ];
        text = text.Replace[ "'", "'" ];
        text = text.Replace[ "\"", ""e;" ];
    
        if[ this.FilterOutput ]
        {
            text = text.Trim[];
    
            // We want to replace consecutive spaces
            // to one space in order to save horizontal width
            if[ this.ReduceConsecutiveSpace ] 
                text = text.Replace["   ", " "];
            if[ this.RemoveNewlines ] 
                text = text.Replace[Environment.NewLine, " "];
    
            base.WriteRaw[ text ];
        }
        else
        {
            base.WriteRaw[ text ];
        }
    }
    3 được ghi đè để ngăn các thuộc tính không mong muốn

Chúng ta hãy xem toàn bộ lớp từng phần

khả năng cấu hình

Bạn có thể định cấu hình HtmlWriter bằng cách sửa đổi khối sau

C#

public class HtmlWriter : XmlTextWriter
{
    /// 
    /// If set to true, it will filter the output
    /// by using tag and attribute filtering,
    /// space reduce etc
    /// 
    public bool FilterOutput = false;
    /// 
    /// If true, it will reduce consecutive   with one instance
    /// 
    public bool ReduceConsecutiveSpace = true;
    /// 
    /// Set the tag names in lower case which are allowed to go to output
    /// 
    public string [] AllowedTags = 
        new string[] { "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"};
    /// 
    /// If any tag found which is not allowed, it is replaced by this tag.
    /// Specify a tag which has least impact on output
    /// 
    public string ReplacementTag = "dd";
    /// 
    /// New lines \r\n are replaced with space 
    /// which saves space and makes the
    /// output compact
    /// 
    public bool RemoveNewlines = true;
    /// 
    /// Specify which attributes are allowed. 
    /// Any other attribute will be discarded
    /// 
    public string [] AllowedAttributes = new string[] 
    { 
        "class", "href", "target", "border", "src", 
        "align", "width", "height", "color", "size" 
    };
}

Phương thức WriteString

C#

/// 
/// The reason why we are overriding
/// this method is, we do not want the output to be
/// encoded for texts inside attribute
/// and inside node elements. For example, all the  
/// gets converted to &nbsp in output. But this does not 
/// apply to HTML. In HTML, we need to have   as it is.
/// 
/// 
public override void WriteString[string text]
{
    // Change all non-breaking space to normal space
    text = text.Replace[ " ", " " ];
    /// When you are reading RSS feed and writing Html, 
    /// this line helps remove those CDATA tags
    text = text.Replace[""];
    text = text.Replace["]]>", ""];

    // Do some encoding of our own because
    // we are going to use WriteRaw which won't
    // do any of the necessary encoding
    text = text.Replace[ "", ">" ];
    text = text.Replace[ "'", "'" ];
    text = text.Replace[ "\"", ""e;" ];

    if[ this.FilterOutput ]
    {
        text = text.Trim[];

        // We want to replace consecutive spaces
        // to one space in order to save horizontal width
        if[ this.ReduceConsecutiveSpace ] 
            text = text.Replace["   ", " "];
        if[ this.RemoveNewlines ] 
            text = text.Replace[Environment.NewLine, " "];

        base.WriteRaw[ text ];
    }
    else
    {
        base.WriteRaw[ text ];
    }
}

ViếtBắt đầuYếu tố. Áp dụng lọc thẻ

C#

public override void WriteStartElement[string prefix, 
    string localName, string ns]
{
    if[ this.FilterOutput ] 
    {
        bool canWrite = false;
        string tagLocalName = localName.ToLower[];
        foreach[ string name in this.AllowedTags ]
        {
            if[ name == tagLocalName ]
            {
                canWrite = true;
                break;
            }
        }
        if[ !canWrite ] 
        localName = "dd";
    }
    base.WriteStartElement[prefix, localName, ns];
}

Phương thức WriteAttributes. Áp dụng lọc thuộc tính

C#

bool canWrite = false;
string attributeLocalName = reader.LocalName.ToLower[];
foreach[ string name in this.AllowedAttributes ]
{
    if[ name == attributeLocalName ]
    {
        canWrite = true;
        break;
    }
}
// If allowed, write the attribute
if[ canWrite ] 
    this.WriteStartAttribute[reader.Prefix, 
    attributeLocalName, reader.NamespaceURI];
while [reader.ReadAttributeValue[]]
{
    if [reader.NodeType == XmlNodeType.EntityReference]
    {
        if[ canWrite ] this.WriteEntityRef[reader.Name];
        continue;
    }
    if[ canWrite ]this.WriteString[reader.Value];
}
if[ canWrite ] this.WriteEndAttribute[];

Phần kết luận

Ứng dụng mẫu là một tiện ích mà bạn có thể sử dụng ngay bây giờ để dọn dẹp các tệp HTML. Bạn có thể sử dụng lớp này trong các ứng dụng như công cụ viết blog nơi bạn cần đăng HTML lên một số dịch vụ web

Giấy phép

Bài viết này, cùng với bất kỳ mã nguồn và tệp liên quan nào, được cấp phép theo Giấy phép Mở Dự án Mã [CPOL]

Bạn có thể chuyển đổi HTML sang XHTML không?

Để chuyển đổi một trang web từ HTML sang XHTML. Bạn phải thêm định nghĩa DOCTYPE vào đầu mỗi trang mã . Mỗi tài liệu phải có khai báo DOCTYPE để trang web được xác thực. 2. Tất cả các thẻ và thuộc tính phải là chữ thường.

XHTML là gì và cách thêm JavaScript vào tài liệu XHTML?

XHTML là viết tắt của EXtensible HyperText Markup Language. Đó là sự giao thoa giữa ngôn ngữ HTML và XML . XHTML gần giống với HTML nhưng nó chặt chẽ hơn HTML. XHTML là HTML được định nghĩa là một ứng dụng XML.

Tại sao nên sử dụng XHTML thay vì HTML?

XHTML đã được phát triển để giúp HTML có thể mở rộng và linh hoạt hơn để hoạt động với các định dạng dữ liệu khác [chẳng hạn như XML]. Ngoài ra, các trình duyệt bỏ qua các lỗi trong trang HTML và cố gắng hiển thị trang web ngay cả khi nó có một số lỗi trong đánh dấu. Vì vậy, XHTML đi kèm với việc xử lý lỗi chặt chẽ hơn nhiều.

Sự khác biệt giữa HTML và XHTML là gì?

HTML là ngôn ngữ đánh dấu tiêu chuẩn để tạo các trang web, trong khi XHTML là phiên bản HTML chuẩn hơn và chặt chẽ hơn . Cả HTML và XHTML đều bao gồm nhiều tính năng, chẳng hạn như hỗ trợ đa phương tiện, kiểu dáng và viết kịch bản.

Chủ Đề