Javascript XMLSerializer case sensitive

2019-09-10 16:55发布

问题:

I'm generating a KML document in Javascript and i'm trying to use XMLSerializer to generate the XML file but it's generating all lower case tags even though i create the tags in capital in the DOM.

Is it the DOM that mangles the capitalization or the XMLSerializer? Is there any way to get around it or am I missing something? I've tried this in both Chrome and Firefox.

The KML document is to be imported into Google Earth and it seems it doesn't accept lower case tags.

回答1:

Based on testing in FF4, the following will work:

  1. Use document.createElementNS ("http://www.opengis.net/kml/2.2", elementName) instead of document.createElement(elementName).

  2. Use elt.appendChild (document.createTextNode (text)) instead of elt.innerHTML = text.



回答2:

The following works for me (preserving case) in FF 5 beta in an XHTML page:

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>test</title>
        <script type="text/javascript">
            function test() {
                var kml = document.getElementsByTagName("kml").item(0);
                window.alert (new XMLSerializer().serializeToString(kml));
            }
        </script>
    </head>
    <body onload="test()">
<kml id="kml" xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>KML Samples</name>
    <open>1</open>
    <description>samples</description>
    <Style id="downArrowIcon">
      <IconStyle>
        <Icon>
          <href>http://maps.google.com/mapfiles/kml/pal4/icon28.png</href>
        </Icon>
      </IconStyle>
    </Style>
  </Document>
</kml>
    </body>
</html>


回答3:

It doesn't matter if you add elements with capital letters, the DOM manages them always in lower case. Just check it with firebug, you won't see uppercase tags.

In case your doctype is set to XHTML it even breaks standard compliance.

in XHTML attributes and elements must be all lower-case

UPDATE: just checked following:

var test = document.createElement("DIV");
// test.outerHTML returns "<div></div>"

So already when you create the element, it's being parsed and converted to lowercase.