2012-05-06 21 views
12

Ho hundered di file HTML che devono essere convocati in XML. Stiamo usando questi HTML per servire i contenuti per le applicazioni, ma ora dobbiamo servire questi contenuti come XML.Conversione da HTML a XML

file HTML sono contiene, tabelle, div, l'immagine di, p, il B o forti tag, ecc ..

I Googled e trovato alcune applicazioni ma non poteva ancora achive.

Puoi suggerire un modo per convertire questi contenuti di file in XML?

+0

Dai un'occhiata a [questo post] (http://stackoverflow.com/a/85922/938089). Quindi, dai un'occhiata da vicino al [quarto commento] (http://stackoverflow.com/questions/84556/#comment1436887_85922). Perché vuoi convertire HTML in XML? –

+0

@RobW lo controllerò. Stavamo servendo l'HTML come contenuto per alcune applicazioni, ma ora dobbiamo fungere da XML. –

+0

@RobW, anche io conosco le differenze tra XML e HTML. Ma ho bisogno di analizzare il suo contenuto e inserire XML. –

risposta

15

ho avuto successo utilizzando utility a riga di comando tidy. Su Linux l'ho installato rapidamente con apt-get install tidy. Poi il comando:

tidy -q -asxml --numeric-entities yes source.html >file.xml

ha dato un file XML, che sono stato in grado di elaborare con processore XSLT. Tuttavia avevo bisogno di impostare correttamente xhtml1 dtds.

Questa è la loro homepage: html-tidy.org (e l'eredità uno: HTML Tidy)

+4

C'è anche xmllint -html -xmlout –

+2

Lo uso anche a volte. Penso che dovresti fare una risposta separata da esso. – Jarekczek

+0

rimuove javascript dal file html – Alaa

1

Ricordare che HTML e XML sono due concetti distinti nell'albero dei linguaggi di markup. Non puoi esattamente replace HTML with XML. XML può essere visto come una forma generalizzata di HTML, ma anche questo è impreciso. Utilizzi principalmente HTML per visualizzare dati e XML per trasportare (o archiviare) i dati.

Questo link è utile: How to read HTML as XML?

More here - difference between HTML and XML

+0

HTML __is__ XML. – bfontaine

+10

@boudou. No, XHTML è XML, HTML no. – Bruno

+1

Quindi cosa suggerisci? Se inizialmente converto HTML in XHTML, posso convertirlo facilmente in XML? –

2

ho trovato un modo per convertire (anche male) html in XML ben formato. Ho iniziato a basare questo sulla funzione loadHTML DOM. Tuttavia nel corso del tempo si sono verificati diversi problemi e ho ottimizzato e aggiunto patch per correggere gli effetti collaterali.

function tryToXml($dom,$content) { 
    if(!$content) return false; 

    // xml well formed content can be loaded as xml node tree 
    $fragment = $dom->createDocumentFragment(); 
    // wonderfull appendXML to add an XML string directly into the node tree! 

    // aappendxml will fail on a xml declaration so manually skip this when occurred 
    if(substr($content,0, 5) == '<?xml') { 
     $content = substr($content,strpos($content,'>')+1); 
     if(strpos($content,'<')) { 
     $content = substr($content,strpos($content,'<')); 
     } 
    } 

    // if appendXML is not working then use below htmlToXml() for nasty html correction 
    if([email protected]$fragment->appendXML($content)) { 
     return $this->htmlToXml($dom,$content); 
    } 

    return $fragment; 
    } 



    // convert content into xml 
    // dom is only needed to prepare the xml which will be returned 
    function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) { 

    // no xml when html is empty 
    if(!$content) return false; 

    // real content and possibly it needs encoding 
    if($needEncoding) { 
     // no need to convert character encoding as loadHTML will respect the content-type (only) 
     $content = '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content; 
    } 

    // return a dom from the content 
    $domInject = new DOMDocument("1.0", "UTF-8"); 
    $domInject->preserveWhiteSpace = false; 
    $domInject->formatOutput = true; 

    // html type 
    try { 
     @$domInject->loadHTML($content); 
    } catch(Exception $e){ 
     // do nothing and continue as it's normal that warnings will occur on nasty HTML content 
    } 
     // to check encoding: echo $dom->encoding 
     $this->reworkDom($domInject); 

    if($bodyOnly) { 
     $fragment = $dom->createDocumentFragment(); 

     // retrieve nodes within /html/body 
     foreach($domInject->documentElement->childNodes as $elementLevel1) { 
     if($elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE) { 
     foreach($elementLevel1->childNodes as $elementInject) { 
      $fragment->insertBefore($dom->importNode($elementInject, true)); 
     } 
     } 
     } 
    } else { 
     $fragment = $dom->importNode($domInject->documentElement, true); 
    } 

    return $fragment; 
    } 



    protected function reworkDom($node, $level = 0) { 

     // start with the first child node to iterate 
     $nodeChild = $node->firstChild; 

     while ($nodeChild) { 
      $nodeNextChild = $nodeChild->nextSibling; 

      switch ($nodeChild->nodeType) { 
       case XML_ELEMENT_NODE: 
        // iterate through children element nodes 
        $this->reworkDom($nodeChild, $level + 1); 
        break; 
       case XML_TEXT_NODE: 
       case XML_CDATA_SECTION_NODE: 
        // do nothing with text, cdata 
        break; 
       case XML_COMMENT_NODE: 
        // ensure comments to remove - sign also follows the w3c guideline 
        $nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue); 
        break; 
       case XML_DOCUMENT_TYPE_NODE: // 10: needs to be removed 
       case XML_PI_NODE: // 7: remove PI 
        $node->removeChild($nodeChild); 
        $nodeChild = null; // make null to test later 
        break; 
       case XML_DOCUMENT_NODE: 
        // should not appear as it's always the root, just to be complete 
        // however generate exception! 
       case XML_HTML_DOCUMENT_NODE: 
        // should not appear as it's always the root, just to be complete 
        // however generate exception! 
       default: 
        throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]"); 
      } 
      $nodeChild = $nodeNextChild; 
     } ; 
    } 

Ora questo consente anche di aggiungere più pezzi html in un file XML che avevo bisogno di usare da solo. In generale, può essere utilizzato in questo modo:

 $c='<p>test<font>two</p>'; 
    $dom=new DOMDocument('1.0', 'UTF-8'); 

$n=$dom->appendChild($dom->createElement('info')); // make a root element 

if($valueXml=tryToXml($dom,$c)) { 
    $n->appendChild($valueXml); 
} 
    echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>'; 

In questo esempio '<p>test<font>two</p>' sarà bene essere in output in XML ben formato come '<info><p>test<font>two</font></p></info>'. Il tag radice info viene aggiunto in quanto consentirà anche di convertire '<p>one</p><p>two</p>' che non è XML in quanto non ha un elemento radice. Tuttavia, se html ha sicuramente un elemento radice, il tag radice aggiuntiva <info> può essere saltato.

Con questo sto ottenendo un vero e proprio codice XML da HTML non strutturato e persino danneggiato!

Spero sia un po 'chiaro e potrebbe contribuire ad altre persone ad usarlo.

+1

È questo codice PHP? –