1
votes

I have to read the encoding and version from xml document.

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

i.e; encoding should return as UTF-8 and version as 1.0

Input will be valid xml document.

Please help

2
I'm voting to close this question as off-topic because the person has made no effort whatsoever to solve the problem on his/her own.Dan Bracuk

2 Answers

3
votes

The Java XML parser that ColdFusion uses exposes that information via getEncoding() and getVersion(). This'll work on ColdFusion, but not on Lucee or Railo.

    <cfsavecontent variable="foo">
    <?xml version="1.0" encoding="UTF-8"?>
        <note>
            <to>Tove</to>
            <from>Jani</from>
            <heading>Reminder</heading>
            <body>Don't forget me this weekend!</body>
        </note>
    </cfsavecontent>

    <cfset xml = XMLParse(trim(foo))>

    <cfdump var="#{
        encoding: xml.getEncoding(),
        version: xml.getVersion()
    }#">

Tested on ColdFusion 10 & 11.

1
votes

You can convert the xml to string and then do regular expression to get the version and encoding.

<cfsavecontent variable="foo">
<?xml version="1.0" encoding="UTF-8"?>
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>
</cfsavecontent>

<cfset xml = XMLParse(trim(foo))>   
<cfset xmlString = ToString(xml)>


<cfset Version = REMatchNoCase("version=""(.+?)""", xmlString) >
<cfset version = REMatch("(?s)"".*?""", Version[1]) >
<cfset version = replace(version[1],'"',"","all") > 
<cfdump var="#version#">


<cfset encoding = REMatchNoCase("encoding=""(.+)""", xmlString) >
<cfset encoding = REMatch("(?s)"".*?""", encoding[1]) >
<cfset encoding = replace(encoding[1],'"',"","all") >   
<cfdump var="#encoding#">