Editar documento HTML – Editar archivo HTML – C#
Como ya mencionamos en el artículo Crear documento HTML, la implementación del HTMLDocument, así como todo el DOM, se basan en el estándar WHATWG DOM. Por lo tanto, es fácil usar Aspose.HTML for .NET teniendo un conocimiento básico de los lenguajes HTML y JavaScript.
Espacio de nombres DOM
Un árbol DOM es una representación en memoria de un documento. El DOM es una API para acceder y manipular el contenido de los documentos. Los documentos HTML constan de un árbol que contiene varios tipos de nodos cuya raíz es un Document. El espacio de nombres DOM se representa con los siguientes tipos de datos fundamentales:
Data type | Description |
---|---|
Document | The Document class represents the entire HTML, XML or SVG document. Conceptually, it is the root of the document tree and provides the primary access to the document’s data. |
EventTarget | The EventTarget class is implemented by all Nodes in an implementation that supports the DOM Event Model. An EventTarget object represents a target to which an event can be dispatched when something has occurred. |
Node | The Node class is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. |
Element | The element type is based on node and represents a base class for HTML, XML or SVG DOM. |
Attr | The Attr class represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a schema associated with the document. |
La siguiente es una breve lista de métodos API útiles proporcionados por los tipos de datos principales:
Method | Description |
---|---|
Document.GetElementById(elementId ) | The method, when invoked, must return the first element whose ID is elementId and null if there is no such element otherwise. |
Document.GetElementsByTagName(tagname ) | The method must return the list of elements with the given name. |
Document.CreateElement(localname ) | The method creates an element of the type specified, or an HTMLUnknownElement if tagname isn’t recognized. |
Node.AppendChild(node ) | The method adds a node to the end of the list of children of a specified parent node. |
Element.SetAttribute(name, value ) | Sets the value of an attribute on the specified element. |
Element.GetAttribute(name ) | The method returns the value of a specified attribute on the element. |
Element.InnerHTML | The property returns a fragment of markup contained within the element. |
Para obtener una lista completa de interfaces y métodos representados en el espacio de nombres DOM, visite Fuente de referencia API.
Editar HTML
Hay muchas formas de editar HTML utilizando nuestra biblioteca. Puede modificar el documento insertando nuevos nodos, eliminando o editando el contenido de los nodos existentes. Si necesita crear un nuevo nodo, debe invocar los siguientes métodos:
Method | Description |
---|---|
Document.CreateCDATASection(data ) | Creates a CDATASection node whose value is the specified string. |
Document.CreateComment(data ) | Creates a Comment node given the specified string. |
Document.CreateDocumentFragment() | Creates an empty DocumentFragment object. |
Document.CreateElement(localname ) | Creates an element of the type specified. |
Document.CreateEntityReference(name ) | Creates an EntityReference object. |
Document.CreateProcessingInstruction(target, data ) | Creates an ProcessingInstruction with the specified name and data. |
Document.CreateTextNode(data ) | Creates a Text node given the specified string. |
Una vez que haya creado nuevos nodos, existen varios métodos en el DOM que pueden ayudarlo a insertar nodos en el árbol del documento. La siguiente lista describe la forma más común de insertar nodos:
Method | Description |
---|---|
Node.InsertBefore(node, child ) | Inserts the node before the reference child node. |
Node.AppendChild(node ) | Adds the node to the list of children of the current node. |
Node.RemoveChild(child ) | Removes the child node from the list of children. |
Element.Remove() | Removes this instance from the HTML DOM tree. |
Puede descargar los ejemplos completos y los archivos de datos desde GitHub.
Editar un árbol de documentos
Los documentos HTML constan de un árbol de elementos. Cada elemento se indica en el código fuente mediante una etiqueta inicial, como <body>
, y una etiqueta final, como </body>
. Los elementos pueden tener atributos que controlan cómo funcionan. Aspose.HTML for .NET API admite un conjunto de elementos HTML definidos en HTML Standard, junto con reglas sobre cómo se pueden anidar los elementos.
Considere pasos simples para crear y editar HTML. El documento contendrá un párrafo de texto con un atributo id
:
- Crear una instancia de un documento HTML.
- Crear un elemento de párrafo
<p>
. - Establecer el atributo
id
para el elemento de párrafo. - Crear un nodo de texto.
- Añade el texto al párrafo.
- Añade el párrafo al cuerpo del documento.
- Guarde el documento HTML en un archivo.
1// Edit HTML document using DOM Tree
2
3// Create an instance of an HTML document
4using (HTMLDocument document = new HTMLDocument())
5{
6 HTMLElement body = document.Body;
7
8 // Create a paragraph element
9 HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
10
11 // Set a custom attribute
12 p.SetAttribute("id", "my-paragraph");
13
14 // Create a text node
15 Text text = document.CreateTextNode("my first paragraph");
16
17 // Attach the text to the paragraph
18 p.AppendChild(text);
19
20 // Attach the paragraph to the document body
21 body.AppendChild(p);
22
23 // Save the HTML document to a file
24 document.Save(Path.Combine(OutputDir, "edit-document-tree.html"));
25}
Echemos un vistazo a la creación de un documento HTML más complejo. Cada documento HTML se representa como un árbol de nodos y algunos de los nodos de un árbol pueden tener hijos. El siguiente fragmento de código muestra cómo editar un documento HTML usando el árbol DOM y la funcionalidad mencionada anteriormente:
1// Create and add new HTML elements using C#
2
3// Create an instance of an HTML document
4using (HTMLDocument document = new HTMLDocument())
5{
6 // Create a <style> element and assign the green color for all elements with class-name equals 'gr'.
7 Element style = document.CreateElement("style");
8 style.TextContent = ".gr { color: green }";
9
10 // Find the document <head> element and append the <style> element to it
11 Element head = document.GetElementsByTagName("head").First();
12 head.AppendChild(style);
13
14 // Create a paragraph element with class-name 'gr'.
15 HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
16 p.ClassName = "gr";
17
18 // Create a text node
19 Text text = document.CreateTextNode("Hello World!!");
20
21 // Append the text node to the paragraph
22 p.AppendChild(text);
23
24 // Append the paragraph to the document <body> element
25 document.Body.AppendChild(p);
26
27 // Save the HTML document to a file
28 document.Save(Path.Combine(OutputDir, "using-dom.html"));
29
30 // Create an instance of the PDF output device and render the document into this device
31 using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "using-dom.pdf")))
32 {
33 // Render HTML to PDF
34 document.RenderTo(device);
35 }
36}
Uso de propiedades InnerHTML y OuterHTML
Tener objetos DOM le brinda una poderosa herramienta para manipular un documento HTML. Sin embargo, a veces es mucho mejor trabajar solo con System.String. El siguiente fragmento de código le muestra cómo utilizar las propiedades InnerHTML y OuterHTML para editar HTML.
1// Edit HTML body content and get modified document as string
2
3// Create an instance of an HTML document
4using (HTMLDocument document = new HTMLDocument())
5{
6 // Write the content of the HTML document into the console output
7 Console.WriteLine(document.DocumentElement.OuterHTML); // output: <html><head></head><body></body></html>
8
9 // Set the content of the body element
10 document.Body.InnerHTML = "<p>HTML is the standard markup language for Web pages.</p>";
11
12 // Set an html variable for the document content viewing
13 string html = document.DocumentElement.OuterHTML;
14
15 // Write the content of the HTML document into the console output
16 Console.WriteLine(html); // output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>
17}
Editar CSS
Las hojas de estilo en cascada (CSS) son un lenguaje de hojas de estilo que se utiliza para describir cómo se ven las páginas web en el navegador. CSS se puede agregar a documentos HTML de forma en línea, interna y externa. Por lo tanto, puede establecer el estilo único para un solo elemento HTML usando CSS en línea, o para que varias páginas web compartan formato especificando el CSS relevante en un archivo .css separado. Aspose.HTML no solo admite CSS listo para usar, sino que también le brinda instrumentos para administrar estilos de documentos sobre la marcha antes de convertir el documento HTML a otros formatos, como se muestra a continuación.
CSS en línea – Inline CSS
Cuando CSS se escribe utilizando el atributo style
dentro de una etiqueta HTML, se denomina “CSS de estilo en línea”. El CSS en línea le permite aplicar un estilo individual a un elemento HTML a la vez. Puede configurar CSS en un elemento HTML utilizando el atributo style
con las propiedades CSS definidas en él.
En el siguiente fragmento de código, puede ver cómo especificar propiedades de estilo CSS para un elemento HTML <p>
.
1// How to set inline CSS styles in an HTML element using C#
2
3// Create an instance of an HTML document with specified content
4string content = "<p>InlineCSS </p>";
5using (HTMLDocument document = new HTMLDocument(content, "."))
6{
7 // Find the paragraph element to set a style
8 HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
9
10 // Set the style attribute
11 paragraph.SetAttribute("style", "font-size:250%; font-family:verdana; color:#cd66aa");
12
13 // Save the HTML document to a file
14 document.Save(Path.Combine(OutputDir, "edit-inline-css.html"));
15
16 // Create an instance of PDF output device and render the document into this device
17 using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "edit-inline-css.pdf")))
18 {
19 // Render HTML to PDF
20 document.RenderTo(device);
21 }
22}
En este ejemplo particular, el color, el tamaño de fuente y la familia de fuente se aplican al elemento <p>
. El fragmento de la página pdf renderizada se ve así:
CSS interno
La opción de estilo CSS interno es popular para aplicar propiedades a páginas individuales encerrando todos los estilos en el elemento <style>
colocado en el <head>
de los documentos HTML.
1// Edit HTML with internal CSS using C#
2
3// Create an instance of an HTML document with specified content
4string content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";
5using (HTMLDocument document = new HTMLDocument(content, "."))
6{
7 Element style = document.CreateElement("style");
8 style.TextContent = ".frame1 { margin-top:50px; margin-left:50px; padding:20px; width:360px; height:90px; background-color:#a52a2a; font-family:verdana; color:#FFF5EE;} \r\n" +
9 ".frame2 { margin-top:-90px; margin-left:160px; text-align:center; padding:20px; width:360px; height:100px; background-color:#ADD8E6;}";
10
11 // Find the document header element and append the style element to the header
12 Element head = document.GetElementsByTagName("head").First();
13 head.AppendChild(style);
14
15 // Find the first paragraph element to inspect the styles
16 HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
17 paragraph.ClassName = "frame1";
18
19 // Find the last paragraph element to inspect the styles
20 HTMLElement lastParagraph = (HTMLElement)document.GetElementsByTagName("p").Last();
21 lastParagraph.ClassName = "frame2";
22
23 // Set a color to the first paragraph
24 paragraph.Style.FontSize = "250%";
25 paragraph.Style.TextAlign = "center";
26
27 // Set a font-size to the last paragraph
28 lastParagraph.Style.Color = "#434343";
29 lastParagraph.Style.FontSize= "150%";
30 lastParagraph.Style.FontFamily = "verdana";
31
32 // Save the HTML document to a file
33 document.Save(Path.Combine(OutputDir, "edit-internal-css.html"));
34
35 // Create the instance of the PDF output device and render the document into this device
36 using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "edit-internal-css.pdf")))
37 {
38 // Render HTML to PDF
39 document.RenderTo(device);
40 }
41}
En este ejemplo, usamos CSS interno y también declaramos propiedades de estilo adicionales para elementos individuales usando la propiedad Style de la clase HTMLElement. La figura ilustra el fragmento del archivo “edit-internal-css.pdf” renderizado:
CSS externo – Internal CSS
Se puede escribir una hoja de estilo externa en cualquier editor de texto y guardarla con una extensión .css. Es un archivo CSS independiente que está vinculado desde una página web. La ventaja del CSS externo es que se puede crear una vez y las reglas se pueden aplicar a varias páginas web.
Ejemplo 1
Veamos un ejemplo de una realización CSS externa en la que utilizamos un enlace a una dirección URL de un archivo CSS:
1// How to use an external CSS file in HTML using Aspose.HTML for .NET
2
3// Create an instance of HTML document with specified content
4string htmlContent = "<link rel=\"stylesheet\" href=\"https://docs.aspose.com/html/net/edit-html-document/external.css\" type=\"text/css\" />\r\n" +
5 "<div class=\"rect1\" ></div>\r\n" +
6 "<div class=\"rect2\" ></div>\r\n" +
7 "<div class=\"frame\">\r\n" +
8 "<p style=\"font-size:2.5em; color:#ae4566;\"> External CSS </p>\r\n" +
9 "<p class=\"rect3\"> An external CSS can be created once and applied to multiple web pages</p></div>\r\n";
10
11using (HTMLDocument document = new HTMLDocument(htmlContent, "."))
12{
13 // Save the HTML document to a file
14 document.Save(Path.Combine(OutputDir, "external-css.html"));
15
16 // Create the instance of the PDF output device and render the document into this device
17 using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "external-css.pdf")))
18 {
19 // Render HTML to PDF
20 document.RenderTo(device);
21 }
22}
El resultado de la aplicación de CSS externo se ve así:
Ejemplo 2
Puede escribir contenido para un archivo CSS en una cadena y guardarlo en un archivo vinculado separado, como se muestra en el siguiente ejemplo:
1// Edit HTML with external CSS using C#
2
3// Prepare content of a CSS file
4string styleContent = ".flower1 { width:120px; height:40px; border-radius:20px; background:#4387be; margin-top:50px; } \r\n" +
5 ".flower2 { margin-left:0px; margin-top:-40px; background:#4387be; border-radius:20px; width:120px; height:40px; transform:rotate(60deg); } \r\n" +
6 ".flower3 { transform:rotate(-60deg); margin-left:0px; margin-top:-40px; width:120px; height:40px; border-radius:20px; background:#4387be; }\r\n" +
7 ".frame { margin-top:-50px; margin-left:310px; width:160px; height:50px; font-size:2em; font-family:Verdana; color:grey; }\r\n";
8
9// Prepare a linked CSS file
10File.WriteAllText("flower.css", styleContent);
11
12// Create an instance of an HTML document with specified content
13string htmlContent = "<link rel=\"stylesheet\" href=\"flower.css\" type=\"text/css\" /> \r\n" +
14 "<div style=\"margin-top: 80px; margin-left:250px; transform: scale(1.3);\" >\r\n" +
15 "<div class=\"flower1\" ></div>\r\n" +
16 "<div class=\"flower2\" ></div>\r\n" +
17 "<div class=\"flower3\" ></div></div>\r\n" +
18 "<div style = \"margin-top: -90px; margin-left:120px; transform:scale(1);\" >\r\n" +
19 "<div class=\"flower1\" style=\"background: #93cdea;\"></div>\r\n" +
20 "<div class=\"flower2\" style=\"background: #93cdea;\"></div>\r\n" +
21 "<div class=\"flower3\" style=\"background: #93cdea;\"></div></div>\r\n" +
22 "<div style =\"margin-top: -90px; margin-left:-80px; transform: scale(0.7);\" >\r\n" +
23 "<div class=\"flower1\" style=\"background: #d5effc;\"></div>\r\n" +
24 "<div class=\"flower2\" style=\"background: #d5effc;\"></div>\r\n" +
25 "<div class=\"flower3\" style=\"background: #d5effc;\"></div></div>\r\n" +
26 "<p class=\"frame\">External</p>\r\n" +
27 "<p class=\"frame\" style=\"letter-spacing:10px; font-size:2.5em \"> CSS </p>\r\n";
28
29using (HTMLDocument document = new HTMLDocument(htmlContent, "."))
30{
31 // Save the HTML document to a file
32 document.Save(Path.Combine(OutputDir, "edit-external-css.html"));
33}
Este ejemplo muestra cómo crear gráficos CSS desde cero. La visualización del archivo “edit-external-css.html” se muestra en la figura:
Como se mencionó, la aplicación más común de CSS es diseñar páginas web escritas en HTML y otros lenguajes de marcado. Pero más allá del diseño web, puedes usar CSS para crear algunos gráficos bonitos, como el que te mostramos arriba. El concepto fundamental del dibujo CSS es utilizar el radio del borde, la rotación y la ubicación para crear curvas y formas de forma creativa.
Puede descargar los ejemplos completos y los archivos de datos desde GitHub.