Sunday, January 29, 2006

E4X to DOM and Back Again

If you're like me, some of the time, you'll work in E4X. Other times, you'll use DOM methods. Occasionally you'll want to switch back and forth from one to the other. Here's how to do the roundtrip.

// create E4X XML object
e4x = <div>Hello World!</div>;

// serialize it
serialzed = e4x.toXMLString();

// create DOM object
dom =
( new DOMParser() ).parseFromString(
serialzed, 'application/xml' );

// make it into a string again
serialized = ( new XMLSerializer() ).serializeToString(dom);

// back to E4X XML object
e4x = new XML( serialized );

Eventually we can expect to see support for a syntax like e4x = new XML( dom ), but this has yet to be implemented in Firefox.

Thursday, January 26, 2006

OOo namespace hell -- or is it heaven?

The .odt format continues the tradition of using, in essence, a zip archive containing mostly XML. And as in 1.x releases of OOo, the content of your document is in content.xml within the archive.

The number of declared namespaces has grown since .sxw days. Even in the smallest .odt file, you get this:

<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"

xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0"
xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo=""
xmlns:xsi="" office:version="1.0">

Notice, in particular, the xforms declaration. It's there by default now, mainly because any .odt can double as an xform.

More of which, later.