2008-09-26 3 views
21

Мне нужно преобразовать HTML-документы в действительный XML, желательно XHTML. Каков наилучший способ сделать это? Кто-нибудь знает инструментарий/библиотеку/образец/... что бы это ни помогло мне сделать эту задачу?Как преобразовать HTML в XHTML?

Чтобы быть более понятным здесь, мое приложение должно выполнить преобразование автоматически во время выполнения. Я не ищу инструмент, который помогает мне перемещать некоторые страницы на XHTML вручную.

ответ

23

Convert from HTML to XML with HTML Tidy

Downloadable Binaries

JRoppert, для вашей потребности, я думаю, вы можете захотеть взглянуть на 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

Самый простой способ, чтобы установить Visual Studio IDE для идентификации изменения, которые вам нужно внести. Вы можете сделать это в Visual Studio 2008, перейдя по адресу: Инструменты, параметры, текстовый редактор, HTML, проверка и выбор подходящей цели. Возможно XHTML 1.1 или XHTML 1.0 Transitional.

Для некоторой информации о различных типах, читайте: http://msdn.microsoft.com/en-us/library/aa479043.aspx

Затем вам нужно работать через точку выделенную на вашей странице.

+0

Извините, я не был ясно в своем вопросе. Мне нужно сделать преобразование автоматически во время выполнения. – JRoppert 2008-09-26 10:12:16

6

Вы можете использовать HTML Agility Pack. Его проект с открытым исходным кодом от CodePlex.

4

Validator.nu HTML Parser поставляется с образцовой программой HTML2XML, которая выполняет преобразование с использованием алгоритма синтаксического анализа HTML5 и правил принудительного ввода информации.

4

Использование Html2Xhtml для .NET 4.0:

в памяти строки к строке преобразования:

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

в памяти строки к XDocument преобразования:

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

См http://corsis.sourceforge.net/index.php/Html2Xhtml для получения дополнительной информации.

+0

У меня был тот же самый вопрос и он использовал этот ответ, он прекрасно работает. Специально для преобразования в XElement. – Beaker 2010-06-12 22:23:37

2

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

Html2Xhtml является библиотека .NET, +4,0 для преобразования HTML в XHTML под лицензией GPLv2 или выше.

Я протестировал Html2Xhtml в местной реконструкции большой онлайн-базы данных Европейского Союза. Tidy/Tidy.NET даже не выдавал допустимый результат большую часть времени, HTML-to-XML Chilkat был немного медленным и производил странные результаты (неуместные, отсутствующие, необъяснимые элементы). В попытке найти бесплатный, быстрый и надежный инструмент преобразования я создал эту библиотеку. Он преобразует 2 - 4 раза быстрее, чем все другие библиотеки, которые я тестировал.

Html2Xhtml, объединенный с мощью LINQ to XML, является отличным инструментом для всех широкомасштабных сценариев извлечения данных и веб-сканирования.

2

вы можете конвертировать HTML в XHTML с опрятным исполняемым файлом:

аккуратного -asxhtml -numeric < индекса.html> index.xhml

вы можете проверить реализацию C# here.

Смежные вопросы