2008-09-26 17 views
21

Necesito convertir documentos HTML a XML válido, preferiblemente XHTML. ¿Cuál es la mejor manera de hacer esto? ¿Alguien conoce un kit de herramientas/library/sample/... lo que sea que me ayude a realizar esa tarea?Cómo convertir HTML a XHTML?

Para ser un poco más claro aquí, mi aplicación tiene que hacer la conversión automáticamente en tiempo de ejecución. No busco una herramienta que me ayude a mover algunas páginas a XHTML manualmente.

Respuesta

23

Convert from HTML to XML with HTML Tidy

Downloadable Binaries

JRoppert, para su necesidad, supongo que es posible que desee ver el Sources

c:\temp>tidy -help 
tidy [option...] [file...] [option...] [file...] 
Utility to clean up and pretty print HTML/XHTML/XML 
see http://tidy.sourceforge.net/ 

Options for HTML Tidy for Windows released on 14 February 2006: 

File manipulation 
----------------- 
-output <file>, -o write output to the specified <file> 
<file> 
-config <file>  set configuration options from the specified <file> 
-file <file>, -f write errors to the specified <file> 
<file> 
-modify, -m   modify the original input files 

Processing directives 
--------------------- 
-indent, -i   indent element content 
-wrap <column>, -w wrap text at the specified <column>. 0 is assumed if 
<column>   <column> is missing. When this option is omitted, the 
        default of the configuration option "wrap" applies. 
-upper, -u   force tags to upper case 
-clean, -c   replace FONT, NOBR and CENTER tags by CSS 
-bare, -b   strip out smart quotes and em dashes, etc. 
-numeric, -n  output numeric rather than named entities 
-errors, -e   only show errors 
-quiet, -q   suppress nonessential output 
-omit    omit optional end tags 
-xml    specify the input is well formed XML 
-asxml, -asxhtml convert HTML to well formed XHTML 
-ashtml    force XHTML to well formed HTML 
-access <level>  do additional accessibility checks (<level> = 0, 1, 2, 3). 
        0 is assumed if <level> is missing. 

Character encodings 
------------------- 
-raw    output values above 127 without conversion to entities 
-ascii    use ISO-8859-1 for input, US-ASCII for output 
-latin0    use ISO-8859-15 for input, US-ASCII for output 
-latin1    use ISO-8859-1 for both input and output 
-iso2022   use ISO-2022 for both input and output 
-utf8    use UTF-8 for both input and output 
-mac    use MacRoman for input, US-ASCII for output 
-win1252   use Windows-1252 for input, US-ASCII for output 
-ibm858    use IBM-858 (CP850+Euro) for input, US-ASCII for output 
-utf16le   use UTF-16LE for both input and output 
-utf16be   use UTF-16BE for both input and output 
-utf16    use UTF-16 for both input and output 
-big5    use Big5 for both input and output 
-shiftjis   use Shift_JIS for both input and output 
-language <lang> set the two-letter language code <lang> (for future use) 

Miscellaneous 
------------- 
-version, -v  show the version of Tidy 
-help, -h, -?  list the command line options 
-xml-help   list the command line options in XML format 
-help-config  list all configuration options 
-xml-config   list all configuration options in XML format 
-show-config  list the current configuration settings 

Use --blah blarg for any configuration option "blah" with argument "blarg" 

Input/Output default to stdin/stdout respectively 
Single letter options apart from -f may be combined 
as in: tidy -f errs.txt -imu foo.html 
For further info on HTML see http://www.w3.org/MarkUp 
0

La forma más sencilla es configurar el IDE de Visual Studio para identificar el cambios que necesitas hacer. Puede hacerlo en Visual Studio 2008 visitando: Herramientas, Opciones, Editor de texto, HTML, Validación y eligiendo el destino apropiado. Posiblemente XHTML 1.1 o XHTML 1.0 Transitional.

Por alguna información sobre los diferentes tipos, debe decir: http://msdn.microsoft.com/en-us/library/aa479043.aspx

Luego hay que trabajar a través de los puntos que se destacan en su página.

+0

Lo siento, no estaba claro en mi pregunta. Necesito hacer la conversión automáticamente en tiempo de ejecución. – JRoppert

4

El Validator.nu HTML Parser viene con un programa de ejemplo HTML2XML que realiza la conversión utilizando el algoritmo de análisis HTML5 y las reglas de coerción infoset.

4

Uso Html2Xhtml para .NET 4.0:

Dentro de la memoria de cadena-a-cadena de conversión:

var xhtml = Html2Xhtml.RunAsFilter(stdin => stdin.Write(html)).ReadToEnd(); 

Dentro de la memoria de cadena-a-XDocument conversión:

var xdoc = Html2Xhtml.RunAsFilter(stdin => stdin.Write(html)).ReadToXDocument(); 

Ver http://corsis.sourceforge.net/index.php/Html2Xhtml para más información.

+0

Tuve exactamente la misma pregunta y usé esta respuesta, funciona muy bien. Especialmente para la conversión a XElement. – Beaker

2

http://corsis.sourceforge.net/index.php/Html2Xhtml http://corsis.sourceforge.net/index.php/Html2Xhtml

Html2Xhtml es una biblioteca .NET 4.0 para la conversión de HTML a XHTML licenciado bajo GPLv2 o superior.

Probé Html2Xhtml en la reconstrucción local de una gran base de datos en línea de la Unión Europea. Tidy/Tidy.NET ni siquiera producía resultados válidos la mayor parte del tiempo, el HTML-to-XML de Chilkat era un poco lento y producía resultados extraños (elementos extraviados, faltantes e inexplicables). En un intento por encontrar una herramienta de conversión gratuita, rápida y confiable, creé esta biblioteca. Convierte 2 - 4 veces más rápido que todas las otras bibliotecas que probé.

Html2Xhtml, combinado con la potencia de LINQ to XML, es una herramienta excelente para todos los escenarios de extracción de datos a gran escala y rastreo web.

2

puede convertir HTML a XHTML con el archivo ejecutable ordenada:

ordenada -asxhtml -numeric índice <.html> index.xhml

puede verificar la implementación de C# here.