001package org.hl7.fhir.r5.elementmodel;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.OutputStream;
026import java.util.ArrayList;
027import java.util.Collections;
028import java.util.Comparator;
029import java.util.List;
030
031import javax.xml.parsers.DocumentBuilder;
032import javax.xml.parsers.DocumentBuilderFactory;
033import javax.xml.parsers.SAXParser;
034import javax.xml.parsers.SAXParserFactory;
035import javax.xml.transform.Transformer;
036import javax.xml.transform.TransformerFactory;
037import javax.xml.transform.dom.DOMResult;
038import javax.xml.transform.sax.SAXSource;
039
040import org.hl7.fhir.exceptions.DefinitionException;
041import org.hl7.fhir.exceptions.FHIRException;
042import org.hl7.fhir.exceptions.FHIRFormatError;
043import org.hl7.fhir.r5.elementmodel.Element;
044import org.hl7.fhir.r5.conformance.ProfileUtilities;
045import org.hl7.fhir.r5.context.IWorkerContext;
046import org.hl7.fhir.r5.elementmodel.Element.SpecialElement;
047import org.hl7.fhir.r5.formats.FormatUtilities;
048import org.hl7.fhir.r5.formats.IParser.OutputStyle;
049import org.hl7.fhir.r5.model.DateTimeType;
050import org.hl7.fhir.r5.model.ElementDefinition.PropertyRepresentation;
051import org.hl7.fhir.r5.model.Enumeration;
052import org.hl7.fhir.r5.model.StructureDefinition;
053import org.hl7.fhir.r5.utils.ToolingExtensions;
054import org.hl7.fhir.r5.utils.formats.XmlLocationAnnotator;
055import org.hl7.fhir.r5.utils.formats.XmlLocationData;
056import org.hl7.fhir.utilities.ElementDecoration;
057import org.hl7.fhir.utilities.Utilities;
058import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
059import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
060import org.hl7.fhir.utilities.xhtml.CDANarrativeFormat;
061import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
062import org.hl7.fhir.utilities.xhtml.XhtmlNode;
063import org.hl7.fhir.utilities.xhtml.XhtmlParser;
064import org.hl7.fhir.utilities.xml.IXMLWriter;
065import org.hl7.fhir.utilities.xml.XMLUtil;
066import org.hl7.fhir.utilities.xml.XMLWriter;
067import org.w3c.dom.Document;
068import org.w3c.dom.Node;
069import org.xml.sax.InputSource;
070import org.xml.sax.XMLReader;
071
072public class XmlParser extends ParserBase {
073  private boolean allowXsiLocation;
074
075  public XmlParser(IWorkerContext context) {
076    super(context);
077  }
078
079  
080  public boolean isAllowXsiLocation() {
081    return allowXsiLocation;
082  }
083
084  public void setAllowXsiLocation(boolean allowXsiLocation) {
085    this.allowXsiLocation = allowXsiLocation;
086  }
087
088  public Element parse(InputStream stream) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
089                Document doc = null;
090        try {
091                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
092                // xxe protection
093                factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
094                factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
095                factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
096                factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
097                factory.setXIncludeAware(false);
098                factory.setExpandEntityReferences(false);
099                        
100                factory.setNamespaceAware(true);
101                if (policy == ValidationPolicy.EVERYTHING) {
102                        // use a slower parser that keeps location data
103                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
104                        Transformer nullTransformer = transformerFactory.newTransformer();
105                        DocumentBuilder docBuilder = factory.newDocumentBuilder();
106                        doc = docBuilder.newDocument();
107                        DOMResult domResult = new DOMResult(doc);
108                        SAXParserFactory spf = SAXParserFactory.newInstance();
109                        spf.setNamespaceAware(true);
110                        spf.setValidating(false);
111                // xxe protection
112                  spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
113        spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
114                        SAXParser saxParser = spf.newSAXParser();
115                        XMLReader xmlReader = saxParser.getXMLReader();
116                // xxe protection
117                  xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
118                  xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
119                                
120                        XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
121                        InputSource inputSource = new InputSource(stream);
122                        SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
123                        nullTransformer.transform(saxSource, domResult);
124                } else {
125                        DocumentBuilder builder = factory.newDocumentBuilder();
126                        doc = builder.parse(stream);
127                }
128        } catch (Exception e) {
129      logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
130      doc = null;
131        }
132        if (doc == null)
133                return null;
134        else
135      return parse(doc);
136  }
137
138  private void checkForProcessingInstruction(Document document) throws FHIRFormatError {
139    if (policy == ValidationPolicy.EVERYTHING && FormatUtilities.FHIR_NS.equals(document.getDocumentElement().getNamespaceURI())) {
140      Node node = document.getFirstChild();
141      while (node != null) {
142        if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)
143          logError(line(document), col(document), "(document)", IssueType.INVALID, "No processing instructions allowed in resources", IssueSeverity.ERROR);
144        node = node.getNextSibling();
145      }
146    }
147  }
148
149  
150  private int line(Node node) {
151                XmlLocationData loc = (XmlLocationData) node.getUserData(XmlLocationData.LOCATION_DATA_KEY);
152                return loc == null ? 0 : loc.getStartLine();
153  }
154
155  private int col(Node node) {
156                XmlLocationData loc = (XmlLocationData) node.getUserData(XmlLocationData.LOCATION_DATA_KEY);
157                return loc == null ? 0 : loc.getStartColumn();
158  }
159
160  public Element parse(Document doc) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
161    checkForProcessingInstruction(doc);
162    org.w3c.dom.Element element = doc.getDocumentElement();
163    return parse(element);
164  }
165  
166  public Element parse(org.w3c.dom.Element element) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
167    String ns = element.getNamespaceURI();
168    String name = element.getLocalName();
169    String path = "/"+pathPrefix(ns)+name;
170    
171    StructureDefinition sd = getDefinition(line(element), col(element), ns, name);
172    if (sd == null)
173      return null;
174
175    Element result = new Element(element.getLocalName(), new Property(context, sd.getSnapshot().getElement().get(0), sd));
176    checkElement(element, path, result.getProperty());
177    result.markLocation(line(element), col(element));
178    result.setType(element.getLocalName());
179    parseChildren(path, element, result);
180    result.numberChildren();
181    return result;
182  }
183
184  private String pathPrefix(String ns) {
185    if (Utilities.noString(ns))
186      return "";
187    if (ns.equals(FormatUtilities.FHIR_NS))
188      return "f:";
189    if (ns.equals(FormatUtilities.XHTML_NS))
190      return "h:";
191    if (ns.equals("urn:hl7-org:v3"))
192      return "v3:";
193    return "?:";
194  }
195
196  private boolean empty(org.w3c.dom.Element element) {
197    for (int i = 0; i < element.getAttributes().getLength(); i++) {
198      String n = element.getAttributes().item(i).getNodeName();
199      if (!n.equals("xmlns") && !n.startsWith("xmlns:"))
200        return false;
201    }
202    if (!Utilities.noString(element.getTextContent().trim()))
203      return false;
204    
205    Node n = element.getFirstChild();
206    while (n != null) {
207      if (n.getNodeType() == Node.ELEMENT_NODE)
208        return false;
209      n = n.getNextSibling();
210    }
211    return true;
212  }
213  
214  private void checkElement(org.w3c.dom.Element element, String path, Property prop) throws FHIRFormatError {
215    if (policy == ValidationPolicy.EVERYTHING) {
216      if (empty(element) && FormatUtilities.FHIR_NS.equals(element.getNamespaceURI())) // this rule only applies to FHIR Content
217        logError(line(element), col(element), path, IssueType.INVALID, "Element must have some content", IssueSeverity.ERROR);
218      String ns = FormatUtilities.FHIR_NS;
219      if (ToolingExtensions.hasExtension(prop.getDefinition(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))
220        ns = ToolingExtensions.readStringExtension(prop.getDefinition(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace");
221      else if (ToolingExtensions.hasExtension(prop.getStructure(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))
222        ns = ToolingExtensions.readStringExtension(prop.getStructure(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace");
223      if (!element.getNamespaceURI().equals(ns))
224        logError(line(element), col(element), path, IssueType.INVALID, "Wrong namespace - expected '"+ns+"'", IssueSeverity.ERROR);
225    }
226  }
227
228  public Element parse(org.w3c.dom.Element base, String type) throws Exception {
229    StructureDefinition sd = getDefinition(0, 0, FormatUtilities.FHIR_NS, type);
230    Element result = new Element(base.getLocalName(), new Property(context, sd.getSnapshot().getElement().get(0), sd));
231    String path = "/"+pathPrefix(base.getNamespaceURI())+base.getLocalName();
232    checkElement(base, path, result.getProperty());
233    result.setType(base.getLocalName());
234    parseChildren(path, base, result);
235    result.numberChildren();
236    return result;
237  }
238
239  private void parseChildren(String path, org.w3c.dom.Element node, Element context) throws FHIRFormatError, FHIRException, IOException, DefinitionException {
240        // this parsing routine retains the original order in a the XML file, to support validation
241        reapComments(node, context);
242    List<Property> properties = context.getProperty().getChildProperties(context.getName(), XMLUtil.getXsiType(node));
243
244        String text = XMLUtil.getDirectText(node).trim();
245    if (!Utilities.noString(text)) {
246        Property property = getTextProp(properties);
247        if (property != null) {
248        if ("ED.data[x]".equals(property.getDefinition().getId())) {
249          if ("B64".equals(node.getAttribute("representation"))) {
250            context.getChildren().add(new Element("dataBase64Binary", property, "base64Binary", text).markLocation(line(node), col(node)));
251          } else {
252            context.getChildren().add(new Element("dataString", property, "string", text).markLocation(line(node), col(node)));           
253          }
254        } else {
255          context.getChildren().add(
256              new Element(property.getName(), property, property.getType(), text).markLocation(line(node), col(node)));
257        }
258      } 
259        else {
260        logError(line(node), col(node), path, IssueType.STRUCTURE, "Text should not be present", IssueSeverity.ERROR);
261        }               
262    }
263    
264    for (int i = 0; i < node.getAttributes().getLength(); i++) {
265        Node attr = node.getAttributes().item(i);
266        if (!(attr.getNodeName().equals("xmlns") || attr.getNodeName().startsWith("xmlns:"))) {
267        Property property = getAttrProp(properties, attr.getNodeName());
268        if (property != null) {
269                  String av = attr.getNodeValue();
270                  if (ToolingExtensions.hasExtension(property.getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"))
271                        av = convertForDateFormatFromExternal(ToolingExtensions.readStringExtension(property.getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"), av);
272                        if (property.getName().equals("value") && context.isPrimitive())
273                                context.setValue(av);
274                        else
275                    context.getChildren().add(new Element(property.getName(), property, property.getType(), av).markLocation(line(node), col(node)));
276        } else {
277          boolean ok = false;
278          if (FormatUtilities.FHIR_NS.equals(node.getNamespaceURI())) {
279            if (attr.getLocalName().equals("schemaLocation") && FormatUtilities.NS_XSI.equals(attr.getNamespaceURI())) {
280              ok = ok || allowXsiLocation; 
281            }
282          } else
283            ok = ok || (attr.getLocalName().equals("schemaLocation")); // xsi:schemalocation allowed for non FHIR content
284          ok = ok || (hasTypeAttr(context) && attr.getLocalName().equals("type") && FormatUtilities.NS_XSI.equals(attr.getNamespaceURI())); // xsi:type allowed if element says so
285          if (!ok)  
286            logError(line(node), col(node), path, IssueType.STRUCTURE, "Undefined attribute '@"+attr.getNodeName()+"' on "+node.getNodeName()+" for type "+context.fhirType()+" (properties = "+properties+")", IssueSeverity.ERROR);         
287        }
288        }
289    }
290    
291    Node child = node.getFirstChild();
292    while (child != null) {
293        if (child.getNodeType() == Node.ELEMENT_NODE) {
294                Property property = getElementProp(properties, child.getLocalName());
295                if (property != null) {
296                        if (!property.isChoice() && "xhtml".equals(property.getType())) {
297                          XhtmlNode xhtml;
298                          if (property.getDefinition().hasRepresentation(PropertyRepresentation.CDATEXT)) 
299                            xhtml = new CDANarrativeFormat().convert((org.w3c.dom.Element) child);
300                else 
301              xhtml = new XhtmlParser().setValidatorMode(true).parseHtmlNode((org.w3c.dom.Element) child);
302                                                context.getChildren().add(new Element(property.getName(), property, "xhtml", new XhtmlComposer(XhtmlComposer.XML, false).compose(xhtml)).setXhtml(xhtml).markLocation(line(child), col(child)));
303                        } else {
304                          String npath = path+"/"+pathPrefix(child.getNamespaceURI())+child.getLocalName();
305                                Element n = new Element(child.getLocalName(), property).markLocation(line(child), col(child));
306                                checkElement((org.w3c.dom.Element) child, npath, n.getProperty());
307                                boolean ok = true;
308                                if (property.isChoice()) {
309                                        if (property.getDefinition().hasRepresentation(PropertyRepresentation.TYPEATTR)) {
310                                                String xsiType = ((org.w3c.dom.Element) child).getAttributeNS(FormatUtilities.NS_XSI, "type");
311                                                if (Utilities.noString(xsiType)) {
312                          logError(line(child), col(child), path, IssueType.STRUCTURE, "No type found on '"+child.getLocalName()+'"', IssueSeverity.ERROR);
313                          ok = false;
314                                                } else {
315                                                        if (xsiType.contains(":"))
316                                                                xsiType = xsiType.substring(xsiType.indexOf(":")+1);
317                                                        n.setType(xsiType);
318                                                        n.setExplicitType(xsiType);
319                                                }
320                                        } else
321                                          n.setType(n.getType());
322                                }
323                                context.getChildren().add(n);
324                                if (ok) {
325                                        if (property.isResource())
326                parseResource(npath, (org.w3c.dom.Element) child, n, property);
327                                        else
328                                                parseChildren(npath, (org.w3c.dom.Element) child, n);
329                                }
330                        }
331        } else
332          logError(line(child), col(child), path, IssueType.STRUCTURE, "Undefined element '"+child.getLocalName()+"'", IssueSeverity.ERROR);                    
333        } else if (child.getNodeType() == Node.CDATA_SECTION_NODE){
334        logError(line(child), col(child), path, IssueType.STRUCTURE, "CDATA is not allowed", IssueSeverity.ERROR);                      
335        } else if (!Utilities.existsInList(child.getNodeType(), 3, 8)) {
336        logError(line(child), col(child), path, IssueType.STRUCTURE, "Node type "+Integer.toString(child.getNodeType())+" is not allowed", IssueSeverity.ERROR);
337        }
338        child = child.getNextSibling();
339    }
340  }
341
342  private Property getElementProp(List<Property> properties, String nodeName) {
343                List<Property> propsSortedByLongestFirst = new ArrayList<Property>(properties);
344                // sort properties according to their name longest first, so .requestOrganizationReference comes first before .request[x]
345                // and therefore the longer property names get evaluated first
346                Collections.sort(propsSortedByLongestFirst, new Comparator<Property>() {
347                        @Override
348                        public int compare(Property o1, Property o2) {
349                                return o2.getName().length() - o1.getName().length();
350                        }
351                });
352        for (Property p : propsSortedByLongestFirst)
353                if (!p.getDefinition().hasRepresentation(PropertyRepresentation.XMLATTR) && !p.getDefinition().hasRepresentation(PropertyRepresentation.XMLTEXT)) {
354                  if (p.getName().equals(nodeName)) 
355                                  return p;
356                  if (p.getName().endsWith("[x]") && nodeName.length() > p.getName().length()-3 && p.getName().substring(0, p.getName().length()-3).equals(nodeName.substring(0, p.getName().length()-3))) 
357                                  return p;
358                }
359        return null;
360        }
361
362        private Property getAttrProp(List<Property> properties, String nodeName) {
363        for (Property p : properties)
364                if (p.getName().equals(nodeName) && p.getDefinition().hasRepresentation(PropertyRepresentation.XMLATTR)) 
365                                return p;
366        return null;
367  }
368
369        private Property getTextProp(List<Property> properties) {
370        for (Property p : properties)
371                if (p.getDefinition().hasRepresentation(PropertyRepresentation.XMLTEXT)) 
372                                return p;
373        return null;
374        }
375
376        private String convertForDateFormatFromExternal(String fmt, String av) throws FHIRException {
377        if ("v3".equals(fmt)) {
378                DateTimeType d = DateTimeType.parseV3(av);
379                return d.asStringValue();
380        } else
381                throw new FHIRException("Unknown Data format '"+fmt+"'");
382        }
383
384  private String convertForDateFormatToExternal(String fmt, String av) throws FHIRException {
385    if ("v3".equals(fmt)) {
386      DateTimeType d = new DateTimeType(av);
387      return d.getAsV3();
388    } else
389      throw new FHIRException("Unknown Date format '"+fmt+"'");
390  }
391
392  private void parseResource(String string, org.w3c.dom.Element container, Element parent, Property elementProperty) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
393        org.w3c.dom.Element res = XMLUtil.getFirstChild(container);
394    String name = res.getLocalName();
395    StructureDefinition sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(name, context.getOverrideVersionNs()));
396    if (sd == null)
397      throw new FHIRFormatError("Contained resource does not appear to be a FHIR resource (unknown name '"+res.getLocalName()+"')");
398    parent.updateProperty(new Property(context, sd.getSnapshot().getElement().get(0), sd), SpecialElement.fromProperty(parent.getProperty()), elementProperty);
399    parent.setType(name);
400    parseChildren(res.getLocalName(), res, parent);
401        }
402
403        private void reapComments(org.w3c.dom.Element element, Element context) {
404          Node node = element.getPreviousSibling();
405          while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
406                if (node.getNodeType() == Node.COMMENT_NODE)
407                        context.getComments().add(0, node.getTextContent());
408                node = node.getPreviousSibling();
409          }
410                node = element.getLastChild();
411                while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
412                        node = node.getPreviousSibling();
413                }
414                while (node != null) {
415                        if (node.getNodeType() == Node.COMMENT_NODE)
416                                context.getComments().add(node.getTextContent());
417                        node = node.getNextSibling();
418                }
419        }
420
421  private boolean isAttr(Property property) {
422    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
423      if (r.getValue() == PropertyRepresentation.XMLATTR) {
424        return true;
425      }
426    }
427    return false;
428  }
429
430  private boolean isCdaText(Property property) {
431    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
432      if (r.getValue() == PropertyRepresentation.CDATEXT) {
433        return true;
434      }
435    }
436    return false;
437  }
438
439  private boolean isTypeAttr(Property property) {
440    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
441      if (r.getValue() == PropertyRepresentation.TYPEATTR) {
442        return true;
443      }
444    }
445    return false;
446  }
447
448  private boolean isText(Property property) {
449                for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
450                        if (r.getValue() == PropertyRepresentation.XMLTEXT) {
451                                return true;
452                        }
453                }
454                return false;
455  }
456
457        @Override
458  public void compose(Element e, OutputStream stream, OutputStyle style, String base) throws IOException, FHIRException {
459          XMLWriter xml = new XMLWriter(stream, "UTF-8");
460    xml.setSortAttributes(false);
461    xml.setPretty(style == OutputStyle.PRETTY);
462    xml.start();
463    xml.setDefaultNamespace(e.getProperty().getNamespace());
464    if (hasTypeAttr(e))
465      xml.namespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
466    composeElement(xml, e, e.getType(), true);
467    xml.end();
468
469  }
470
471  private boolean hasTypeAttr(Element e) {
472    if (isTypeAttr(e.getProperty()))
473      return true;
474    for (Element c : e.getChildren()) {
475      if (hasTypeAttr(c))
476        return true;
477    }
478    return false;
479  }
480
481
482  public void compose(Element e, IXMLWriter xml) throws Exception {
483    xml.start();
484    xml.setDefaultNamespace(e.getProperty().getNamespace());
485    composeElement(xml, e, e.getType(), true);
486    xml.end();
487  }
488
489  private void composeElement(IXMLWriter xml, Element element, String elementName, boolean root) throws IOException, FHIRException {
490    if (showDecorations) {
491      @SuppressWarnings("unchecked")
492      List<ElementDecoration> decorations = (List<ElementDecoration>) element.getUserData("fhir.decorations");
493      if (decorations != null)
494        for (ElementDecoration d : decorations)
495          xml.decorate(d);
496    }
497    for (String s : element.getComments()) {
498      xml.comment(s, true);
499    }
500    if (isText(element.getProperty())) {
501      if (linkResolver != null)
502        xml.link(linkResolver.resolveProperty(element.getProperty()));
503      xml.enter(elementName);
504      xml.text(element.getValue());
505      xml.exit(elementName);   
506    } else if (!element.hasChildren() && !element.hasValue()) {
507      if (element.getExplicitType() != null)
508        xml.attribute("xsi:type", element.getExplicitType());
509      xml.element(elementName);
510    } else if (element.isPrimitive() || (element.hasType() && isPrimitive(element.getType()))) {
511      if (element.getType().equals("xhtml")) {
512        String rawXhtml = element.getValue();
513        if (isCdaText(element.getProperty())) {
514          new CDANarrativeFormat().convert(xml, element.getXhtml());
515        } else {
516          xml.escapedText(rawXhtml);
517          xml.anchor("end-xhtml");
518        }
519      } else if (isText(element.getProperty())) {
520        if (linkResolver != null)
521          xml.link(linkResolver.resolveProperty(element.getProperty()));
522        xml.text(element.getValue());
523      } else {
524        if (isTypeAttr(element.getProperty()) && !Utilities.noString(element.getType())) {
525          xml.attribute("xsi:type", element.getType());
526        }
527        if (element.hasValue()) {
528          if (linkResolver != null)
529            xml.link(linkResolver.resolveType(element.getType()));
530        xml.attribute("value", element.getValue());
531        }
532        if (linkResolver != null)
533          xml.link(linkResolver.resolveProperty(element.getProperty()));
534                                if (element.hasChildren()) {
535                                        xml.enter(elementName);
536                                        for (Element child : element.getChildren()) 
537                                                composeElement(xml, child, child.getName(), false);
538                                        xml.exit(elementName);
539                                } else
540          xml.element(elementName);
541      }
542    } else {
543      if (isTypeAttr(element.getProperty()) && !Utilities.noString(element.getType())) {
544        xml.attribute("xsi:type", element.getType());
545      }
546      for (Element child : element.getChildren()) {
547        if (isAttr(child.getProperty())) {
548          if (linkResolver != null)
549            xml.link(linkResolver.resolveType(child.getType()));
550          String av = child.getValue();
551          if (ToolingExtensions.hasExtension(child.getProperty().getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"))
552            av = convertForDateFormatToExternal(ToolingExtensions.readStringExtension(child.getProperty().getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"), av);
553          xml.attribute(child.getName(), av);
554      }
555      }
556      if (linkResolver != null)
557        xml.link(linkResolver.resolveProperty(element.getProperty()));
558      xml.enter(elementName);
559      if (!root && element.getSpecial() != null) {
560        if (linkResolver != null)
561          xml.link(linkResolver.resolveProperty(element.getProperty()));
562        xml.enter(element.getType());
563      }
564      for (Element child : element.getChildren()) {
565        if (isText(child.getProperty())) {
566          if (linkResolver != null)
567            xml.link(linkResolver.resolveProperty(element.getProperty()));
568          xml.text(child.getValue());
569        } else if (!isAttr(child.getProperty()))
570          composeElement(xml, child, child.getName(), false);
571      }
572            if (!root && element.getSpecial() != null)
573        xml.exit(element.getType());
574      xml.exit(elementName);
575    }
576  }
577
578}