elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Ver documento XML en árbol
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ver documento XML en árbol  (Leído 1,743 veces)
FJDA


Desconectado Desconectado

Mensajes: 321


Ver Perfil
Ver documento XML en árbol
« en: 11 Abril 2019, 20:38 pm »

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
  1.        'Crear un nuevo documento XML.
  2.        Dim xmlDoc As XmlDocument = New XmlDocument
  3.        'Crear la etiqueta html.
  4.        Dim xmlRoot As XmlElement = xmlDoc.CreateElement("html")
  5.        xmlDoc.AppendChild(xmlRoot)
  6.  
  7.        'Crea la etiqueta de encabezado y agrégala al elemento html.
  8.        Dim xmlHead As XmlElement = xmlDoc.CreateElement("head")
  9.        xmlRoot.AppendChild(xmlHead)
  10.  
  11.        'Crea la etiqueta del título, configura su texto como "Tabla de base de datos"
  12.        'y anexarlo debajo del elemento cabeza.
  13.  
  14.        Dim xmlTitle As XmlElement = xmlDoc.CreateElement("title")
  15.        xmlTitle.AppendChild(xmlDoc.CreateTextNode("tabla de prueba"))
  16.        xmlHead.AppendChild(xmlTitle)
  17.  
  18.  
  19.        Dim xmlCSSStyle As XmlElement = xmlDoc.CreateElement("style")
  20.        xmlCSSStyle.AppendChild(xmlDoc.CreateTextNode("td{background-color: olive;}"))
  21.        xmlHead.AppendChild(xmlCSSStyle)
  22.  
  23.        ' <html>
  24.        '       <head>
  25.        '           <title> Tabla de base de datos </title>
  26.        '           <style>
  27.        '               td{background-color: olive;}
  28.        '           </style>
  29.        '       </head>
  30.        '</html>
  31.  
  32.        ' Create the body element and append it to the root.
  33.        Dim xmlBody As XmlElement = xmlDoc.CreateElement("body")
  34.        xmlRoot.AppendChild(xmlBody)
  35.  
  36.        ' Create the table and append it.
  37.        Dim xmlTable As XmlElement = xmlDoc.CreateElement("table")
  38.        xmlBody.AppendChild(xmlTable)
  39.  
  40.        '' Create the rows.
  41.        For I = 1 To 2
  42.            Dim xmlRow As XmlElement = xmlDoc.CreateElement("tr")
  43.            xmlTable.AppendChild(xmlRow)
  44.            Dim xmlCell As XmlElement = xmlDoc.CreateElement("td")
  45.            xmlCell.AppendChild(xmlDoc.CreateTextNode("contenido"))
  46.            xmlRow.AppendChild(xmlCell)
  47.        Next
  48.  
  49.  
  50.        WebBrowser1.DocumentText = xmlDoc.OuterXml
  51.  

Así es como queda el código HTML

Código
  1. <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>
  2.  

Me ayudaría se visualizara así:
Código
  1. <!DOCTYPE html>
  2. <title>tabla de prueba</title>
  3. <style>td{background-color: olive;}</style>
  4. </head>
  5. <tr>
  6. <td>contenido</td>
  7. </tr>
  8. <tr>
  9. <td>contenido</td>
  10. </tr>
  11. </table>
  12. </body>
  13. </html>
  14.  

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
  1.      Dim docHTML As XDocument = New XDocument
  2.        Dim docType As XDocumentType = New XDocumentType("html", Nothing, Nothing, Nothing)
  3.        docHTML.Add(docType) '<!DOCTYPE html >
  4.  
  5.        Dim HTML As XElement = New XElement("html", New XElement("head", New XElement("title", "HTML de prueba")), New XElement("body"))
  6.        Dim HEAD As XElement = HTML.Element("head")
  7.        Dim BODY As XElement = HTML.Element("body")
  8.  
  9.        Dim etiquetaStyle As XElement = New XElement("style", vbCrLf,
  10.                                                     "body{background-color: red;}", vbCrLf,
  11.                                                     "h1{font-style: italic}", vbCrLf)
  12.        Dim script As XElement = New XElement("script", "")
  13.        HEAD.Add(New XElement(etiquetaStyle))
  14.  
  15.        Dim h1 As XElement = New XElement("h1", "Hola mundo")
  16.        h1.SetAttributeValue("class", "titulo1")
  17.        BODY.Add(New XElement(h1))
  18.        docHTML.Add(HTML)
  19.  
  20.  
  21.        TextBox1.Text = docHTML.ToString()
  22.        WebBrowser1.DocumentText = docHTML.ToString()
  23.  

Esto quedaría así:
Código
  1. <!DOCTYPE html >
  2.  <head>
  3.   <title>HTML de prueba</title>
  4.    <style>
  5. body{background-color: red;}
  6. h1{font-style: italic}
  7.  </head>
  8.  <body>
  9.    <h1>Hola mundo</h1>
  10.  </body>
  11. </html>
  12.  

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
  1. h1.SetAttributeValue("class", "titulo1")
  2.  

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

Espero le sirvan saludos


Acabo de averiguar que es posible crear las etiquetas de la siguiente manera:
Código
  1.    Dim TABLECLAS1 As XElement = New XElement(<table>
  2.                                                      <tr>
  3.                                                          <td>Mercurio</td>
  4.                                                          <td>Venus</td>
  5.                                                      </tr>
  6.                                                      <tr>
  7.                                                          <td>Mercurio</td>
  8.                                                          <td>Venus</td>
  9.                                                      </tr>
  10.                                                  </table>)
  11.  
Me ha parecido muy curioso así que posteo.



« Última modificación: 12 Abril 2019, 05:09 am por FJDA » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
Re: Ver documento XML en árbol
« Respuesta #1 en: 12 Abril 2019, 12:51 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
  1. ' Namespace DevCase.Core.Xml.Tools
  2.  
  3.    Partial Public NotInheritable Class XmlUtil
  4.  
  5. #Region " Public Methods "
  6.  
  7.        ''' ----------------------------------------------------------------------------------------------------
  8.        ''' <summary>
  9.        ''' Beautifies the contents of an Xml document.
  10.        ''' </summary>
  11.        ''' ----------------------------------------------------------------------------------------------------
  12.        ''' <example> This is a code example.
  13.        ''' <code>
  14.        ''' Dim enc As Encoding = Encoding.Default
  15.        '''
  16.        ''' Dim unformattedXmlDocument As String =
  17.        '''     File.ReadAllText("C:\Unformatted Document.xml", enc)
  18.        '''
  19.        ''' Dim formattedXmlDocument As String =
  20.        '''     XmlBeautifier(xmlText:=unformattedXmlDocument,
  21.        '''                   indentChars:=New String(" "c, 2),
  22.        '''                   indentOnAttributes:=True,
  23.        '''                   enc:=enc)
  24.        '''
  25.        ''' File.WriteAllText("C:\Formatted Document.xml", formattedXmlDocument, enc)
  26.        ''' </code>
  27.        ''' </example>
  28.        ''' ----------------------------------------------------------------------------------------------------
  29.        ''' <param name="xmlText">
  30.        ''' The Xml text content.
  31.        ''' It can be an entire document or a fragment.
  32.        ''' </param>
  33.        '''
  34.        ''' <param name="indentChars">
  35.        ''' The string that is used to indent the Xml.
  36.        ''' <para></para>
  37.        ''' Default value is <see cref="ControlChars.Tab"/>
  38.        ''' </param>
  39.        '''
  40.        ''' <param name="indentOnAttributes">
  41.        ''' If set to <see langword="True"/>, attributes will be separated by newlines.
  42.        ''' </param>
  43.        '''
  44.        ''' <param name="enc">
  45.        ''' The Xml text encoding to use.
  46.        ''' <para></para>
  47.        ''' Default value is <see cref="Encoding.Default"/>.
  48.        ''' </param>
  49.        ''' ----------------------------------------------------------------------------------------------------
  50.        ''' <returns>
  51.        ''' The beautified Xml text.
  52.        ''' </returns>
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <exception cref="ArgumentNullException">
  55.        ''' xmlText
  56.        ''' </exception>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        <DebuggerStepThrough>
  59.        Public Shared Function XmlBeautifier(ByVal xmlText As String,
  60.                                             Optional ByVal indentChars As String = "",
  61.                                             Optional ByVal indentOnAttributes As Boolean = False,
  62.                                             Optional ByVal enc As Encoding = Nothing) As String
  63.  
  64.            If String.IsNullOrEmpty(xmlText) OrElse String.IsNullOrWhiteSpace(xmlText) Then
  65.                Throw New ArgumentNullException(paramName:=NameOf(xmlText))
  66.  
  67.            Else
  68.                Dim xmlDoc As New XmlDocument
  69.                xmlDoc.LoadXml(xmlText)
  70.                Return XmlBeautifier(xmlDoc, indentChars, indentOnAttributes, enc)
  71.  
  72.            End If
  73.  
  74.        End Function
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Beautifies the contents of an Xml document.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <example> This is a code example.
  82.        ''' <code>
  83.        ''' Dim enc As Encoding = Encoding.Default
  84.        '''
  85.        ''' Dim xmlDoc As New XmlDocument
  86.        ''' xmlDoc.LoadXml("xmlText")
  87.        '''
  88.        ''' Dim formattedXmlDocument As String =
  89.        '''     XmlBeautifier(xmlDoc:=xmlDoc,
  90.        '''                   indentChars:=New String(" "c, 2),
  91.        '''                   indentOnAttributes:=True,
  92.        '''                   enc:=enc)
  93.        '''
  94.        ''' File.WriteAllText("C:\Formatted Document.xml", formattedXmlDocument, enc)
  95.        ''' </code>
  96.        ''' </example>
  97.        ''' ----------------------------------------------------------------------------------------------------
  98.        ''' <param name="xmlDoc">
  99.        ''' The Xml document.
  100.        ''' It can be an entire document or a fragment.
  101.        ''' </param>
  102.        '''
  103.        ''' <param name="indentChars">
  104.        ''' The string that is used to indent the Xml.
  105.        ''' <para></para>
  106.        ''' Default value is <see cref="ControlChars.Tab"/>
  107.        ''' </param>
  108.        '''
  109.        ''' <param name="indentOnAttributes">
  110.        ''' If set to <see langword="True"/>, attributes will be separated by newlines.
  111.        ''' </param>
  112.        '''
  113.        ''' <param name="enc">
  114.        ''' The Xml text encoding to use.
  115.        ''' <para></para>
  116.        ''' Default value is <see cref="Encoding.Default"/>.
  117.        ''' </param>
  118.        ''' ----------------------------------------------------------------------------------------------------
  119.        ''' <returns>
  120.        ''' The beautified Xml text.
  121.        ''' </returns>
  122.        ''' ----------------------------------------------------------------------------------------------------
  123.        ''' <exception cref="ArgumentNullException">
  124.        ''' xmlText
  125.        ''' </exception>
  126.        ''' ----------------------------------------------------------------------------------------------------
  127.        <DebuggerStepThrough>
  128.        Public Shared Function XmlBeautifier(ByVal xmlDoc As XmlDocument,
  129.                                             Optional ByVal indentChars As String = "",
  130.                                             Optional ByVal indentOnAttributes As Boolean = False,
  131.                                             Optional ByVal enc As Encoding = Nothing) As String
  132.  
  133.            Dim sb As New Global.System.Text.StringBuilder(capacity:=4096)
  134.            Dim settings As New XmlWriterSettings With {
  135.                .Indent = True,
  136.                .CheckCharacters = True,
  137.                .OmitXmlDeclaration = False,
  138.                .ConformanceLevel = ConformanceLevel.Auto,
  139.                .NamespaceHandling = NamespaceHandling.Default,
  140.                .NewLineHandling = NewLineHandling.Replace,
  141.                .NewLineChars = ControlChars.NewLine,
  142.                .NewLineOnAttributes = indentOnAttributes,
  143.                .IndentChars = If(indentChars, ControlChars.Tab),
  144.                .Encoding = If(enc, Encoding.Default),
  145.                .CloseOutput = True
  146.            }
  147.  
  148.            Using writer As XmlWriter = XmlWriter.Create(sb, settings)
  149.                xmlDoc.WriteContentTo(writer)
  150.                writer.Flush()
  151.            End Using
  152.  
  153.            Return sb.ToString()
  154.  
  155.        End Function
  156.  
  157. #End Region
  158.  
  159.    End Class
  160.  
  161. ' End Namespace

Saludos.


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Mi arbol
Diseño Gráfico
Azielito 1 2,385 Último mensaje 4 Marzo 2004, 02:28 am
por StraTovario
Arbol AVL
Java
arkaos 6 18,959 Último mensaje 31 Mayo 2009, 05:33 am
por arkaos
arbol avl c++
Programación C/C++
jovanny12 2 4,398 Último mensaje 13 Abril 2014, 15:54 pm
por d91
Árbol
Programación C/C++
CGB 2 1,675 Último mensaje 15 Diciembre 2015, 20:16 pm
por 0xFer
leer un documento HTML,cada etiqueta debe guardarse en un nodo de un árbol
Programación C/C++
mcMario 0 1,719 Último mensaje 12 Diciembre 2016, 02:40 am
por mcMario
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines