Skip to content
Advertisement

Transform complex and variable xml

I’ve a complex XML that I want to transform in HTML. Some tags need to be replaced in html tags.

The XML is this:

JavaScript

The text inside the element is variable, which means that the other xml that I parse can completely change.

The output I want is this (for this scenario):

JavaScript

I make a recursive function for parse any single node of xml and replace it in HTML tag (but doesn’t work):

JavaScript

Can anyone help me?

This is an example of a complete xml:

JavaScript

Which has to be transformed into:

JavaScript

Advertisement

Answer

There’s a language specially designed for this task: it’s called XSLT, and you can easily express your desired transformation in XSLT and invoke it from your PHP program. There’s a learning curve, of course, but it’s a much better solution than writing low-level DOM code.

In XSLT you write a set of template rules saying how individual elements should be handled. Many elements in your example are copied through unchanged, so you can start with a default rule that does this:

JavaScript

The “match” part says what part of the input you are matching; the body of the rule says what output to produce. The xsl:apply-templates does a recursive descent to process the children of the current element.

Some of your elements are simply renamed, for example

JavaScript

Some of the rules are a little bit more complex, but still easily expressed:

JavaScript

I hope you agree that this declarative rule-based approach is much clearer than your procedural code; it’s also much easier for someone else to change the rules in six months’ time.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement