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()) || (property.getDefinition()!=null && property.getDefinition().getBase()!=null && "ED.data[x]".equals(property.getDefinition().getBase().getPath()))) {
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                  if (ToolingExtensions.hasExtension(property.getDefinition(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype")) {
313                    xsiType = ToolingExtensions.readStringExtension(property.getDefinition(), "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");
314                    n.setType(xsiType);
315                  } else {
316                          logError(line(child), col(child), path, IssueType.STRUCTURE, "No type found on '"+child.getLocalName()+'"', IssueSeverity.ERROR);
317                          ok = false;
318                  }
319                                                } else {
320                                                        if (xsiType.contains(":"))
321                                                                xsiType = xsiType.substring(xsiType.indexOf(":")+1);
322                                                        n.setType(xsiType);
323                                                        n.setExplicitType(xsiType);
324                                                }
325                                        } else
326                                          n.setType(n.getType());
327                                }
328                                context.getChildren().add(n);
329                                if (ok) {
330                                        if (property.isResource())
331                parseResource(npath, (org.w3c.dom.Element) child, n, property);
332                                        else
333                                                parseChildren(npath, (org.w3c.dom.Element) child, n);
334                                }
335                        }
336        } else
337          logError(line(child), col(child), path, IssueType.STRUCTURE, "Undefined element '"+child.getLocalName()+"'", IssueSeverity.ERROR);                    
338        } else if (child.getNodeType() == Node.CDATA_SECTION_NODE){
339        logError(line(child), col(child), path, IssueType.STRUCTURE, "CDATA is not allowed", IssueSeverity.ERROR);                      
340        } else if (!Utilities.existsInList(child.getNodeType(), 3, 8)) {
341        logError(line(child), col(child), path, IssueType.STRUCTURE, "Node type "+Integer.toString(child.getNodeType())+" is not allowed", IssueSeverity.ERROR);
342        }
343        child = child.getNextSibling();
344    }
345  }
346
347  private Property getElementProp(List<Property> properties, String nodeName) {
348                List<Property> propsSortedByLongestFirst = new ArrayList<Property>(properties);
349                // sort properties according to their name longest first, so .requestOrganizationReference comes first before .request[x]
350                // and therefore the longer property names get evaluated first
351                Collections.sort(propsSortedByLongestFirst, new Comparator<Property>() {
352                        @Override
353                        public int compare(Property o1, Property o2) {
354                                return o2.getName().length() - o1.getName().length();
355                        }
356                });
357        for (Property p : propsSortedByLongestFirst)
358                if (!p.getDefinition().hasRepresentation(PropertyRepresentation.XMLATTR) && !p.getDefinition().hasRepresentation(PropertyRepresentation.XMLTEXT)) {
359                  if (p.getName().equals(nodeName)) 
360                                  return p;
361                  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))) 
362                                  return p;
363                }
364        return null;
365        }
366
367        private Property getAttrProp(List<Property> properties, String nodeName) {
368        for (Property p : properties)
369                if (p.getName().equals(nodeName) && p.getDefinition().hasRepresentation(PropertyRepresentation.XMLATTR)) 
370                                return p;
371        return null;
372  }
373
374        private Property getTextProp(List<Property> properties) {
375        for (Property p : properties)
376                if (p.getDefinition().hasRepresentation(PropertyRepresentation.XMLTEXT)) 
377                                return p;
378        return null;
379        }
380
381        private String convertForDateFormatFromExternal(String fmt, String av) throws FHIRException {
382        if ("v3".equals(fmt)) {
383                DateTimeType d = DateTimeType.parseV3(av);
384                return d.asStringValue();
385        } else
386                throw new FHIRException("Unknown Data format '"+fmt+"'");
387        }
388
389  private String convertForDateFormatToExternal(String fmt, String av) throws FHIRException {
390    if ("v3".equals(fmt)) {
391      DateTimeType d = new DateTimeType(av);
392      return d.getAsV3();
393    } else
394      throw new FHIRException("Unknown Date format '"+fmt+"'");
395  }
396
397  private void parseResource(String string, org.w3c.dom.Element container, Element parent, Property elementProperty) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
398        org.w3c.dom.Element res = XMLUtil.getFirstChild(container);
399    String name = res.getLocalName();
400    StructureDefinition sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(name, context.getOverrideVersionNs()));
401    if (sd == null)
402      throw new FHIRFormatError("Contained resource does not appear to be a FHIR resource (unknown name '"+res.getLocalName()+"')");
403    parent.updateProperty(new Property(context, sd.getSnapshot().getElement().get(0), sd), SpecialElement.fromProperty(parent.getProperty()), elementProperty);
404    parent.setType(name);
405    parseChildren(res.getLocalName(), res, parent);
406        }
407
408        private void reapComments(org.w3c.dom.Element element, Element context) {
409          Node node = element.getPreviousSibling();
410          while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
411                if (node.getNodeType() == Node.COMMENT_NODE)
412                        context.getComments().add(0, node.getTextContent());
413                node = node.getPreviousSibling();
414          }
415                node = element.getLastChild();
416                while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
417                        node = node.getPreviousSibling();
418                }
419                while (node != null) {
420                        if (node.getNodeType() == Node.COMMENT_NODE)
421                                context.getComments().add(node.getTextContent());
422                        node = node.getNextSibling();
423                }
424        }
425
426  private boolean isAttr(Property property) {
427    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
428      if (r.getValue() == PropertyRepresentation.XMLATTR) {
429        return true;
430      }
431    }
432    return false;
433  }
434
435  private boolean isCdaText(Property property) {
436    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
437      if (r.getValue() == PropertyRepresentation.CDATEXT) {
438        return true;
439      }
440    }
441    return false;
442  }
443
444  private boolean isTypeAttr(Property property) {
445    for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
446      if (r.getValue() == PropertyRepresentation.TYPEATTR) {
447        return true;
448      }
449    }
450    return false;
451  }
452
453  private boolean isText(Property property) {
454                for (Enumeration<PropertyRepresentation> r : property.getDefinition().getRepresentation()) {
455                        if (r.getValue() == PropertyRepresentation.XMLTEXT) {
456                                return true;
457                        }
458                }
459                return false;
460  }
461
462        @Override
463  public void compose(Element e, OutputStream stream, OutputStyle style, String base) throws IOException, FHIRException {
464          XMLWriter xml = new XMLWriter(stream, "UTF-8");
465    xml.setSortAttributes(false);
466    xml.setPretty(style == OutputStyle.PRETTY);
467    xml.start();
468    xml.setDefaultNamespace(e.getProperty().getNamespace());
469    if (hasTypeAttr(e))
470      xml.namespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
471    composeElement(xml, e, e.getType(), true);
472    xml.end();
473
474  }
475
476  private boolean hasTypeAttr(Element e) {
477    if (isTypeAttr(e.getProperty()))
478      return true;
479    for (Element c : e.getChildren()) {
480      if (hasTypeAttr(c))
481        return true;
482    }
483    return false;
484  }
485
486
487  public void compose(Element e, IXMLWriter xml) throws Exception {
488    xml.start();
489    xml.setDefaultNamespace(e.getProperty().getNamespace());
490    composeElement(xml, e, e.getType(), true);
491    xml.end();
492  }
493
494  private void composeElement(IXMLWriter xml, Element element, String elementName, boolean root) throws IOException, FHIRException {
495    if (showDecorations) {
496      @SuppressWarnings("unchecked")
497      List<ElementDecoration> decorations = (List<ElementDecoration>) element.getUserData("fhir.decorations");
498      if (decorations != null)
499        for (ElementDecoration d : decorations)
500          xml.decorate(d);
501    }
502    for (String s : element.getComments()) {
503      xml.comment(s, true);
504    }
505    if (isText(element.getProperty())) {
506      if (linkResolver != null)
507        xml.link(linkResolver.resolveProperty(element.getProperty()));
508      xml.enter(elementName);
509      xml.text(element.getValue());
510      xml.exit(elementName);   
511    } else if (!element.hasChildren() && !element.hasValue()) {
512      if (element.getExplicitType() != null)
513        xml.attribute("xsi:type", element.getExplicitType());
514      xml.element(elementName);
515    } else if (element.isPrimitive() || (element.hasType() && isPrimitive(element.getType()))) {
516      if (element.getType().equals("xhtml")) {
517        String rawXhtml = element.getValue();
518        if (isCdaText(element.getProperty())) {
519          new CDANarrativeFormat().convert(xml, element.getXhtml());
520        } else {
521          xml.escapedText(rawXhtml);
522          xml.anchor("end-xhtml");
523        }
524      } else if (isText(element.getProperty())) {
525        if (linkResolver != null)
526          xml.link(linkResolver.resolveProperty(element.getProperty()));
527        xml.text(element.getValue());
528      } else {
529        if (isTypeAttr(element.getProperty()) && !Utilities.noString(element.getType())) {
530          xml.attribute("xsi:type", element.getType());
531        }
532        if (element.hasValue()) {
533          if (linkResolver != null)
534            xml.link(linkResolver.resolveType(element.getType()));
535        xml.attribute("value", element.getValue());
536        }
537        if (linkResolver != null)
538          xml.link(linkResolver.resolveProperty(element.getProperty()));
539                                if (element.hasChildren()) {
540                                        xml.enter(elementName);
541                                        for (Element child : element.getChildren()) 
542                                                composeElement(xml, child, child.getName(), false);
543                                        xml.exit(elementName);
544                                } else
545          xml.element(elementName);
546      }
547    } else {
548      if (isTypeAttr(element.getProperty()) && !Utilities.noString(element.getType())) {
549        xml.attribute("xsi:type", element.getType());
550      }
551      for (Element child : element.getChildren()) {
552        if (isAttr(child.getProperty())) {
553          if (linkResolver != null)
554            xml.link(linkResolver.resolveType(child.getType()));
555          String av = child.getValue();
556          if (ToolingExtensions.hasExtension(child.getProperty().getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"))
557            av = convertForDateFormatToExternal(ToolingExtensions.readStringExtension(child.getProperty().getDefinition(), "http://www.healthintersections.com.au/fhir/StructureDefinition/elementdefinition-dateformat"), av);
558          xml.attribute(child.getName(), av);
559      }
560      }
561      if (linkResolver != null)
562        xml.link(linkResolver.resolveProperty(element.getProperty()));
563      xml.enter(elementName);
564      if (!root && element.getSpecial() != null) {
565        if (linkResolver != null)
566          xml.link(linkResolver.resolveProperty(element.getProperty()));
567        xml.enter(element.getType());
568      }
569      for (Element child : element.getChildren()) {
570        if (isText(child.getProperty())) {
571          if (linkResolver != null)
572            xml.link(linkResolver.resolveProperty(element.getProperty()));
573          xml.text(child.getValue());
574        } else if (!isAttr(child.getProperty()))
575          composeElement(xml, child, child.getName(), false);
576      }
577            if (!root && element.getSpecial() != null)
578        xml.exit(element.getType());
579      xml.exit(elementName);
580    }
581  }
582
583}