Changeset 6615


Ignore:
Timestamp:
07/01/10 04:40:39 (9 years ago)
Author:
dscho
Message:

Avoid "prefix <...> not bound" error when transforming XML

When transforming XML via XSLT, all used namespaces have to be declared.
In other words, if you have a tag "<svi:Custom>", there needs to be
an attribute "xmlns:SVI" in the root element.

If such an attribute does not exist, the XML is malformed. To avoid an
exception, the tags are transformed to contain an underscore instead of
a colon. As these tags are typically in the CustomAttribute section (which
is filtered out anyway), no harm is done by this change.

This works malformed XML generated by Huygens.

Signed-off-by: Johannes Schindelin <johannes.schindelin@…>

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/4.2/components/common/src/loci/common/xml/XMLTools.java

    r6495 r6615  
    3333import java.net.MalformedURLException; 
    3434import java.net.URL; 
     35import java.util.HashSet; 
    3536import java.util.Hashtable; 
     37import java.util.Set; 
    3638import java.util.StringTokenizer; 
     39import java.util.regex.Matcher; 
     40import java.util.regex.Pattern; 
    3741 
    3842import javax.xml.parsers.DocumentBuilder; 
     
    335339  } 
    336340 
     341  /** Replaces NS:tag with NS_tag for undeclared namespaces */ 
     342  public static String avoidUndeclaredNamespaces(String xml) { 
     343    int gt = xml.indexOf('>'); 
     344    if (gt > 0 && xml.startsWith("<?xml ")) 
     345      gt = xml.indexOf('>', gt + 1); 
     346    if (gt > 0) { 
     347      String firstTag = xml.substring(0, gt + 1).toLowerCase(); 
     348      Set namespaces = new HashSet(); 
     349      Pattern pattern = Pattern.compile(" xmlns:(\\w+)"); 
     350      Matcher matcher = pattern.matcher(firstTag); 
     351      while (matcher.find()) 
     352        namespaces.add(matcher.group(1)); 
     353 
     354      pattern = Pattern.compile("</?(\\w+):"); 
     355      matcher = pattern.matcher(xml); 
     356      while (matcher.find()) { 
     357        String namespace = matcher.group(1); 
     358        if (!namespace.startsWith("ns") && !namespaces.contains(namespace.toLowerCase())) 
     359          xml = xml.substring(0, matcher.end() - 1) + "_" + xml.substring(matcher.end()); 
     360      } 
     361    } 
     362    return xml; 
     363  } 
     364 
    337365  /** Transforms the given XML string using the specified XSLT stylesheet. */ 
    338366  public static String transformXML(String xml, Templates xslt) 
    339367    throws IOException 
    340368  { 
     369    xml = avoidUndeclaredNamespaces(xml); 
    341370    return transformXML(new StreamSource(new StringReader(xml)), xslt); 
    342371  } 
Note: See TracChangeset for help on using the changeset viewer.