tylere / pykml

pyKML is a Python package for creating, parsing, manipulating, and validating KML documents.
BSD 3-Clause "New" or "Revised" License
13 stars 9 forks source link

Improve the ability to output CDATA wrapped strings #34

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Example script from Sean:

#!/usr/bin/python
from lxml import etree
from pykml.factory import KML_ElementMaker as KML

TEXT_ELEMENTS = ['description', 'text', 'linkDescription', 'displayName']

def getXmlWithCDATA(obj, cdata_elements):
  # Convert Objectify document to lxml.etree (is there a better way?)
  root = etree.fromstring(etree.tostring(etree.ElementTree(obj)))

  #Create an xpath expression to search for all desired cdata elements
  xpath = '|'.join(map(lambda tag: '//kml:' + tag, cdata_elements))

  results = root.xpath(xpath, namespaces = {'kml': 'http://www.opengis.net/kml/2.2'})
  for element in results:
    element.text = etree.CDATA(element.text)

  return root

kmlobj = KML.kml(
    KML.Document(
        KML.Placemark(
            KML.name('foobar'),
            KML.styleUrl('#big_label'),
            KML.description('<html>'),
            KML.text('<html>'),
            KML.linkDescription('<html>'),
            KML.displayName('<html>')
        )
    )
)

kmlobj_with_cdata = getXmlWithCDATA(kmlobj, TEXT_ELEMENTS)
print etree.tostring(kmlobj_with_cdata, pretty_print=True)

Original issue reported on code.google.com by tylerick...@gmail.com on 22 Feb 2012 at 12:56