Ver documento XML en árbol

(1/1)

FJDA:
Estoy creando un código html mediante xmlDocument. Me gustaría ver el código  en árbol pero se muestra lineal. Aquí dejo un código de ejemplo:

Código
       'Crear un nuevo documento XML.
       Dim xmlDoc As XmlDocument = New XmlDocument
       'Crear la etiqueta html.
       Dim xmlRoot As XmlElement = xmlDoc.CreateElement("html")
       xmlDoc.AppendChild(xmlRoot)
 
       'Crea la etiqueta de encabezado y agrégala al elemento html.
       Dim xmlHead As XmlElement = xmlDoc.CreateElement("head")
       xmlRoot.AppendChild(xmlHead)
 
       'Crea la etiqueta del título, configura su texto como "Tabla de base de datos"
       'y anexarlo debajo del elemento cabeza.
 
       Dim xmlTitle As XmlElement = xmlDoc.CreateElement("title")
       xmlTitle.AppendChild(xmlDoc.CreateTextNode("tabla de prueba"))
       xmlHead.AppendChild(xmlTitle)
 
 
       Dim xmlCSSStyle As XmlElement = xmlDoc.CreateElement("style")
       xmlCSSStyle.AppendChild(xmlDoc.CreateTextNode("td{background-color: olive;}"))
       xmlHead.AppendChild(xmlCSSStyle)
 
       ' <html>
       '       <head>
       '           <title> Tabla de base de datos </title>
       '           <style>
       '               td{background-color: olive;}
       '           </style>
       '       </head>
       '</html>
 
       ' Create the body element and append it to the root.
       Dim xmlBody As XmlElement = xmlDoc.CreateElement("body")
       xmlRoot.AppendChild(xmlBody)
 
       ' Create the table and append it.
       Dim xmlTable As XmlElement = xmlDoc.CreateElement("table")
       xmlBody.AppendChild(xmlTable)
 
       '' Create the rows.
       For I = 1 To 2
           Dim xmlRow As XmlElement = xmlDoc.CreateElement("tr")
           xmlTable.AppendChild(xmlRow)
           Dim xmlCell As XmlElement = xmlDoc.CreateElement("td")
           xmlCell.AppendChild(xmlDoc.CreateTextNode("contenido"))
           xmlRow.AppendChild(xmlCell)
       Next
 
 
       WebBrowser1.DocumentText = xmlDoc.OuterXml
 

Así es como queda el código HTML

Código
<html><head><title>tabla de prueba</title><style>td{background-color: olive;}</style></head><body><table><tr><td>contenido</td></tr><tr><td>contenido</td></tr></table></body></html>
 

Me ayudaría se visualizara así:
Código
<!DOCTYPE html>
<html>
<head>
<title>tabla de prueba</title>
<style>td{background-color: olive;}</style>
</head>
<body>
<table>
<tr>
<td>contenido</td>
</tr>
<tr>
<td>contenido</td>
</tr>
</table>
</body>
</html>
 

gracias de antemano

Tras mucho buscar encontré la manera, usando XDocument  en lugar de XmlDocument. El código es muy flexible así que se puede hacer de muchas maneras, incluso a partir de un DataTable crear una tabla en HTML.

Aquí dejo un ejemplo sencillo de como lo voy a hacer:

Código
     Dim docHTML As XDocument = New XDocument
       Dim docType As XDocumentType = New XDocumentType("html", Nothing, Nothing, Nothing)
       docHTML.Add(docType) '<!DOCTYPE html >
 
       Dim HTML As XElement = New XElement("html", New XElement("head", New XElement("title", "HTML de prueba")), New XElement("body"))
       Dim HEAD As XElement = HTML.Element("head")
       Dim BODY As XElement = HTML.Element("body")
 
       Dim etiquetaStyle As XElement = New XElement("style", vbCrLf,
                                                    "body{background-color: red;}", vbCrLf,
                                                    "h1{font-style: italic}", vbCrLf)
       Dim script As XElement = New XElement("script", "")
       HEAD.Add(New XElement(etiquetaStyle))
 
       Dim h1 As XElement = New XElement("h1", "Hola mundo")
       h1.SetAttributeValue("class", "titulo1")
       BODY.Add(New XElement(h1))
       docHTML.Add(HTML)
 
 
       TextBox1.Text = docHTML.ToString()
       WebBrowser1.DocumentText = docHTML.ToString()
 

Esto quedaría así:
Código
<!DOCTYPE html >
<html>
 <head>
  <title>HTML de prueba</title>
   <style>
body{background-color: red;}
h1{font-style: italic}
</style>
 </head>
 <body>
   <h1>Hola mundo</h1>
 </body>
</html>
 

También se puede escribir concatenado tal como xElement("html", new xElement("head",new xElement...),  xElement("body", new xElement...), pero a la hora de modificar cosas cuando es muy largo se hace tedioso. Prefiero hacerlo por partes.

Para añadir atributos a una etiqueta basta usar SetAttributeValue:

Código
h1.SetAttributeValue("class", "titulo1")
 

y el resultado sería :
Código
<h1 class="titulo1">Hola mundo</h1>
 

Espero le sirvan saludos

Acabo de averiguar que es posible crear las etiquetas de la siguiente manera:
Código
   Dim TABLECLAS1 As XElement = New XElement(<table>
                                                     <tr>
                                                         <td>Mercurio</td>
                                                         <td>Venus</td>
                                                     </tr>
                                                     <tr>
                                                         <td>Mercurio</td>
                                                         <td>Venus</td>
                                                     </tr>
                                                 </table>)
 
Me ha parecido muy curioso así que posteo.

Eleкtro:
Cita de: FJDA en 11 Abril 2019, 20:38 pm

Me ha parecido muy curioso así que posteo.


Un código de uso genérico que te puede servir. Lo he extraido de mi framework comercial: DevCase for .NET Framework

Código
' Namespace DevCase.Core.Xml.Tools
 
   Partial Public NotInheritable Class XmlUtil
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Beautifies the contents of an Xml document.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code>
       ''' Dim enc As Encoding = Encoding.Default
       '''
       ''' Dim unformattedXmlDocument As String =
       '''     File.ReadAllText("C:\Unformatted Document.xml", enc)
       '''
       ''' Dim formattedXmlDocument As String =
       '''     XmlBeautifier(xmlText:=unformattedXmlDocument,
       '''                   indentChars:=New String(" "c, 2),
       '''                   indentOnAttributes:=True,
       '''                   enc:=enc)
       '''
       ''' File.WriteAllText("C:\Formatted Document.xml", formattedXmlDocument, enc)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="xmlText">
       ''' The Xml text content.
       ''' It can be an entire document or a fragment.
       ''' </param>
       '''
       ''' <param name="indentChars">
       ''' The string that is used to indent the Xml.
       ''' <para></para>
       ''' Default value is <see cref="ControlChars.Tab"/>
       ''' </param>
       '''
       ''' <param name="indentOnAttributes">
       ''' If set to <see langword="True"/>, attributes will be separated by newlines.
       ''' </param>
       '''
       ''' <param name="enc">
       ''' The Xml text encoding to use.
       ''' <para></para>
       ''' Default value is <see cref="Encoding.Default"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The beautified Xml text.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="ArgumentNullException">
       ''' xmlText
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Shared Function XmlBeautifier(ByVal xmlText As String,
                                            Optional ByVal indentChars As String = "",
                                            Optional ByVal indentOnAttributes As Boolean = False,
                                            Optional ByVal enc As Encoding = Nothing) As String
 
           If String.IsNullOrEmpty(xmlText) OrElse String.IsNullOrWhiteSpace(xmlText) Then
               Throw New ArgumentNullException(paramName:=NameOf(xmlText))
 
           Else
               Dim xmlDoc As New XmlDocument
               xmlDoc.LoadXml(xmlText)
               Return XmlBeautifier(xmlDoc, indentChars, indentOnAttributes, enc)
 
           End If
 
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Beautifies the contents of an Xml document.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code>
       ''' Dim enc As Encoding = Encoding.Default
       '''
       ''' Dim xmlDoc As New XmlDocument
       ''' xmlDoc.LoadXml("xmlText")
       '''
       ''' Dim formattedXmlDocument As String =
       '''     XmlBeautifier(xmlDoc:=xmlDoc,
       '''                   indentChars:=New String(" "c, 2),
       '''                   indentOnAttributes:=True,
       '''                   enc:=enc)
       '''
       ''' File.WriteAllText("C:\Formatted Document.xml", formattedXmlDocument, enc)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="xmlDoc">
       ''' The Xml document.
       ''' It can be an entire document or a fragment.
       ''' </param>
       '''
       ''' <param name="indentChars">
       ''' The string that is used to indent the Xml.
       ''' <para></para>
       ''' Default value is <see cref="ControlChars.Tab"/>
       ''' </param>
       '''
       ''' <param name="indentOnAttributes">
       ''' If set to <see langword="True"/>, attributes will be separated by newlines.
       ''' </param>
       '''
       ''' <param name="enc">
       ''' The Xml text encoding to use.
       ''' <para></para>
       ''' Default value is <see cref="Encoding.Default"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The beautified Xml text.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="ArgumentNullException">
       ''' xmlText
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Shared Function XmlBeautifier(ByVal xmlDoc As XmlDocument,
                                            Optional ByVal indentChars As String = "",
                                            Optional ByVal indentOnAttributes As Boolean = False,
                                            Optional ByVal enc As Encoding = Nothing) As String
 
           Dim sb As New Global.System.Text.StringBuilder(capacity:=4096)
           Dim settings As New XmlWriterSettings With {
               .Indent = True,
               .CheckCharacters = True,
               .OmitXmlDeclaration = False,
               .ConformanceLevel = ConformanceLevel.Auto,
               .NamespaceHandling = NamespaceHandling.Default,
               .NewLineHandling = NewLineHandling.Replace,
               .NewLineChars = ControlChars.NewLine,
               .NewLineOnAttributes = indentOnAttributes,
               .IndentChars = If(indentChars, ControlChars.Tab),
               .Encoding = If(enc, Encoding.Default),
               .CloseOutput = True
           }
 
           Using writer As XmlWriter = XmlWriter.Create(sb, settings)
               xmlDoc.WriteContentTo(writer)
               writer.Flush()
           End Using
 
           Return sb.ToString()
 
       End Function
 
#End Region
 
   End Class
 
' End Namespace

Saludos.

Navegación

[0] Índice de Mensajes