----- isHidden: false menupriority: 1 kind: article created_at: 2010-05-19T22:20:34+02:00 fr: title: Comment réparer un XML coupé ? fr: subtitle: et comment s'en sortir sans parseur ? en: title: How to repair a cutted XML? en: subtitle: and how to do it without any parsor? author_name: Yann Esposito author_uri: yannesposito.com tags: fr: - arbre en: - tree - HTML - script - ruby ----- en: For my main page, you can see, a list of my latest blog entry. And you have the first part of each article. To accomplish that, I needed to include the begining of the entry and to cut it somewhere. But now, I had to repair this cutted HTML. fr: Sur ma page d'accueil vous pouvez voir la liste des mes derniers articles avec le début de ceux-ci. Pour arriver à faire ça, j'ai besoin de couper le code XHTML de mes pages en plein milieu. Il m'a donc fallu trouver un moyen de les réparer. en: Here is an example: fr: Prenons un exemple :

Introduction

The first paragraph

an image

Another long paragraph

fr: After the cut, I obtain: en: Après avoir coupé, j'obtiens :

Introduction

The first paragraph

[] [div]
[div, div]
[div, div, p]

Introduction [div, div]

[div]
[div, p]

The first paragraph [div]

[div] an image [div, p]

Another long paragraph [div]

[]
en: The algorihm, is then really simple: fr: L'algorithme est alors très simple : let res be the XML as a string ; read res and each time you encouter a tag: if it is an opening one: push it to the stack else if it is a closing one: pop the stack. remove any malformed/cutted tag in the end of res for each tag in the stack, pop it, and write: res = res + closed tag return res en: And `res` contain the repaired XML. fr: Et `res` contiend le XML réparé. en: Finally, this is the code in ruby I use. The `xml` variable contain the cutted XML. fr: Finallement, voici le code en ruby que j'utilise. La variable `xml` contient le XML coupé. # repair cutted XML code by closing the tags # work even if the XML is cut into a tag. # example: # transform '
toto

hello ]*$/m,'') depth-=1 depth.downto(0).each { |x| res<<= %{} } res end en: I don't know if the code can help you, but the raisonning should definitively be known. fr: Je ne sais pas si ce code pourra vous être utile. Par contre le raisonnement pour y parvenir mérite d'être connu.