Example usage for org.w3c.dom Document getFirstChild

List of usage examples for org.w3c.dom Document getFirstChild

Introduction

In this page you can find the example usage for org.w3c.dom Document getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.InputWithPlayControlXML.java

/**
 * Updates the playback information/*from ww  w.j a v  a  2  s .c  o m*/
 *
 * @throws Exception
 */
@Override
public void update() throws IOException, ReceivedMessageParseException {
    if (observer == null) {
        return;
    }

    AbstractConnection com = comReference.get();
    String response = com.sendReceive(wrInput("<Play_Info>GetParam</Play_Info>"));
    Document doc = XMLUtils.xml(response);
    if (doc.getFirstChild() == null) {
        throw new ReceivedMessageParseException("<Play_Info>GetParam failed: " + response);
    }

    PlayInfoState msg = new PlayInfoState();

    Node playInfoNode = XMLUtils.getNode(doc.getFirstChild(), "Play_Info");

    msg.playbackMode = XMLUtils.getNodeContentOrDefault(playInfoNode, "Playback_Info", msg.playbackMode);

    Node metaInfoNode = XMLUtils.getNode(playInfoNode, "Meta_Info");
    if (metaInfoNode != null) {
        String stationElement = YamahaReceiverBindingConstants.INPUT_TUNER.equals(inputID) ? "Radio_Text_A"
                : "Station";
        msg.station = XMLUtils.getNodeContentOrDefault(metaInfoNode, stationElement, msg.station);

        msg.artist = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Artist", msg.artist);
        msg.album = XMLUtils.getNodeContentOrDefault(metaInfoNode, "Album", msg.album);

        String songElement = YamahaReceiverBindingConstants.INPUT_SPOTIFY.equals(inputID) ? "Track" : "Song";
        msg.song = XMLUtils.getNodeContentOrDefault(metaInfoNode, songElement, msg.song);
    }

    if (YamahaReceiverBindingConstants.INPUT_SPOTIFY.equals(inputID)) {
        //<YAMAHA_AV rsp="GET" RC="0">
        //    <Spotify>
        //        <Play_Info>
        //            <Feature_Availability>Ready</Feature_Availability>
        //            <Playback_Info>Play</Playback_Info>
        //            <Meta_Info>
        //                <Artist>Way Out West</Artist>
        //                <Album>Tuesday Maybe</Album>
        //                <Track>Tuesday Maybe</Track>
        //            </Meta_Info>
        //            <Album_ART>
        //                <URL>/YamahaRemoteControl/AlbumART/AlbumART3929.jpg</URL>
        //                <ID>39290</ID>
        //                <Format>JPEG</Format>
        //            </Album_ART>
        //            <Input_Logo>
        //                <URL_S>/YamahaRemoteControl/Logos/logo005.png</URL_S>
        //                <URL_M></URL_M>
        //                <URL_L></URL_L>
        //            </Input_Logo>
        //        </Play_Info>
        //    </Spotify>
        //</YAMAHA_AV>

        // Spotify input supports song cover image
        String songImageUrl = XMLUtils.getNodeContentOrDefault(playInfoNode, "Album_ART/URL", "");
        if (StringUtils.isNotEmpty(songImageUrl)) {
            msg.songImageUrl = String.format("http://%s%s", com.getHost(), songImageUrl);
        }
    }

    logger.trace("Playback: {}, Station: {}, Artist: {}, Album: {}, Song: {}, SongImageUrl: {}",
            msg.playbackMode, msg.station, msg.artist, msg.album, msg.song, msg.songImageUrl);

    observer.playInfoUpdated(msg);
}

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.ZoneControlXML.java

@Override
public void update() throws IOException, ReceivedMessageParseException {
    if (observer == null) {
        return;//w  w w  .  ja v  a 2s .co m
    }

    AbstractConnection com = comReference.get();
    String response = com.sendReceive(XMLUtils.wrZone(zone, "<Basic_Status>GetParam</Basic_Status>"));
    Document doc = XMLUtils.xml(response);
    if (doc.getFirstChild() == null) {
        throw new ReceivedMessageParseException("<Basic_Status>GetParam failed: " + response);
    }
    Node basicStatus = XMLUtils.getNode(doc.getFirstChild(), zone + "/Basic_Status");

    String value;

    ZoneControlState state = new ZoneControlState();

    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Power_Control/Power", "");
    state.power = "On".equalsIgnoreCase(value);

    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Input/Input_Sel", "");
    // ToDo: See the fixme in the class description
    state.inputID = XMLUtils.convertNameToID(value);

    if (StringUtils.isBlank(state.inputID)) {
        throw new ReceivedMessageParseException(
                "Expected inputID. Failed to read Input/Input_Sel_Item_Info/Src_Name");
    }

    // Some receivers may use Src_Name instead?
    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Input/Input_Sel_Item_Info/Title", "");
    state.inputName = value;

    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Surround/Program_Sel/Current/Sound_Program", "");
    state.surroundProgram = value;

    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Volume/Lvl/Val",
            String.valueOf(YamahaReceiverBindingConstants.VOLUME_MIN));
    state.volume = Float.parseFloat(value) * .1f; // in DB
    state.volume = (state.volume + -YamahaReceiverBindingConstants.VOLUME_MIN) * 100.0f
            / YamahaReceiverBindingConstants.VOLUME_RANGE; // in percent
    if (state.volume < 0 || state.volume > 100) {
        logger.error("Received volume is out of range: {}", state.volume);
        state.volume = 0;
    }

    value = XMLUtils.getNodeContentOrDefault(basicStatus, "Volume/Mute", "");
    state.mute = "On".equalsIgnoreCase(value);

    logger.trace("Zone {} state - power: {}, input: {}, mute: {}, surroundProgram: {}, volume: {}", zone,
            state.power, state.inputID, state.mute, state.surroundProgram, state.volume);

    observer.zoneStateChanged(state);
}

From source file:org.openhab.habdroid.model.OpenHABSitemapPage.java

public OpenHABSitemapPage(Document document) {
    Node rootNode = document.getFirstChild();
    if (rootNode == null)
        return;/*from   w  ww .j  ava  2  s  .com*/
    mRootWidget = new OpenHAB1Widget();
    mRootWidget.setType("root");
    if (rootNode.hasChildNodes()) {
        NodeList childNodes = rootNode.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeName().equals("widget")) {
                OpenHABWidget newOpenHABWidget = OpenHAB1Widget.createOpenHABWidgetFromNode(mRootWidget,
                        childNode);
                mWidgets.add(newOpenHABWidget);
            } else if (childNode.getNodeName().equals("title")) {
                this.setTitle(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("id")) {
                this.setPageId(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("icon")) {
                this.setIcon(childNode.getTextContent());
            } else if (childNode.getNodeName().equals("link")) {
                this.setLink(childNode.getTextContent());
            }
        }
    }

}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
  * Parse XML sitemap page and show it//  w  w w  .j av a2  s  .com
  *
  * @param  content   XML as a text
  * @return      void
  */
public void processContent(String content) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document;
        openHABWidgetAdapter.stopVideoWidgets();
        openHABWidgetAdapter.stopImageRefresh();
        // TODO: fix crash with null content
        if (content != null) {
            document = builder.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));
        } else {
            Log.e(TAG, "processContent: content == null");
            return;
        }
        Node rootNode = document.getFirstChild();
        openHABWidgetDataSource.setSourceNode(rootNode);
        widgetList.clear();
        // As we change the page we need to stop all videos on current page
        // before going to the new page. This is quite dirty, but is the only
        // way to do that...
        for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) {
            widgetList.add(w);
        }
        openHABWidgetAdapter.notifyDataSetChanged();
        setTitle(openHABWidgetDataSource.getTitle());
        setProgressBarIndeterminateVisibility(false);
        // Set widget list index to saved or zero position
        // This would mean we got widget and command from nfc tag, so we need to do some automatic actions!
        if (this.nfcWidgetId != null && this.nfcCommand != null) {
            Log.d(TAG, "Have widget and command, NFC action!");
            OpenHABWidget nfcWidget = this.openHABWidgetDataSource.getWidgetById(this.nfcWidgetId);
            OpenHABItem nfcItem = nfcWidget.getItem();
            // Found widget with id from nfc tag and it has an item
            if (nfcWidget != null && nfcItem != null) {
                // TODO: Perform nfc widget action here
                if (this.nfcCommand.equals("TOGGLE")) {
                    if (nfcItem.getType().equals("RollershutterItem")) {
                        if (nfcItem.getStateAsBoolean())
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "UP");
                        else
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "DOWN");
                    } else {
                        if (nfcItem.getStateAsBoolean())
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "OFF");
                        else
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "ON");
                    }
                } else {
                    this.openHABWidgetAdapter.sendItemCommand(nfcItem, this.nfcCommand);
                }
            }
            this.nfcWidgetId = null;
            this.nfcCommand = null;
            if (this.nfcAutoClose) {
                finish();
            }
        }
        getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Widget clicked " + String.valueOf(position));
                OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position);
                if (openHABWidget.hasLinkedPage()) {
                    // Widget have a page linked to it
                    String[] splitString;
                    splitString = openHABWidget.getLinkedPage().getTitle().split("\\[|\\]");
                    navigateToPage(openHABWidget.getLinkedPage().getLink(), splitString[0]);
                }
            }

        });
        getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Widget long-clicked " + String.valueOf(position));
                OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position);
                Log.d(TAG, "Widget type = " + openHABWidget.getType());
                if (openHABWidget.getType().equals("Switch") || openHABWidget.getType().equals("Selection")
                        || openHABWidget.getType().equals("Colorpicker")) {
                    OpenHABWidgetListActivity.this.selectedOpenHABWidget = openHABWidget;
                    AlertDialog.Builder builder = new AlertDialog.Builder(OpenHABWidgetListActivity.this);
                    builder.setTitle(R.string.nfc_dialog_title);
                    OpenHABNFCActionList nfcActionList = new OpenHABNFCActionList(
                            OpenHABWidgetListActivity.this.selectedOpenHABWidget);
                    builder.setItems(nfcActionList.getNames(), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent writeTagIntent = new Intent(
                                    OpenHABWidgetListActivity.this.getApplicationContext(),
                                    OpenHABWriteTagActivity.class);
                            writeTagIntent.putExtra("sitemapPage",
                                    OpenHABWidgetListActivity.this.displayPageUrl);
                            writeTagIntent.putExtra("widget",
                                    OpenHABWidgetListActivity.this.selectedOpenHABWidget.getId());
                            OpenHABNFCActionList nfcActionList = new OpenHABNFCActionList(
                                    OpenHABWidgetListActivity.this.selectedOpenHABWidget);
                            writeTagIntent.putExtra("command", nfcActionList.getCommands()[which]);
                            startActivityForResult(writeTagIntent, 0);
                            Util.overridePendingTransition(OpenHABWidgetListActivity.this, false);
                            OpenHABWidgetListActivity.this.selectedOpenHABWidget = null;
                        }
                    });
                    builder.show();
                    return true;
                }
                return true;
            }
        });
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    showPage(displayPageUrl, true);
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListFragment.java

/**
 * Parse XML sitemap page and show it//www .  j  a va 2s  .  c o  m
 *
 *
 * @return      void
 */
public void processContent(String responseString, boolean longPolling) {

    Log.d(TAG, "processContent() " + this.displayPageUrl);
    Log.d(TAG, "isAdded = " + isAdded());
    Log.d(TAG, "responseString.length() = " + (responseString != null ? responseString.length() : -1));

    // We can receive empty response, probably when no items was changed
    // so we needn't process it
    if (responseString == null || responseString.length() == 0) {
        showPage(displayPageUrl, true);
        return;
    }

    // As we change the page we need to stop all videos on current page
    // before going to the new page. This is quite dirty, but is the only
    // way to do that...
    openHABWidgetAdapter.stopVideoWidgets();
    openHABWidgetAdapter.stopImageRefresh();
    // If openHAB verion = 1 get page from XML
    if (mActivity.getOpenHABVersion() == 1) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(responseString)));
            if (document != null) {
                Node rootNode = document.getFirstChild();
                openHABWidgetDataSource.setSourceNode(rootNode);
                widgetList.clear();
                for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) {
                    // Remove frame widgets with no label text
                    if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel()))
                        continue;
                    widgetList.add(w);
                }
            } else {
                Log.e(TAG, "Got a null response from openHAB");
                showPage(displayPageUrl, false);
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            Log.d(TAG, "responseString:\n" + String.valueOf(responseString));
            Log.e(TAG, e.getMessage(), e);
        }
        // Later versions work with JSON
    } else {
        try {
            JSONObject pageJson = new JSONObject(responseString);
            openHABWidgetDataSource.setSourceJson(pageJson);
            widgetList.clear();
            for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) {
                // Remove frame widgets with no label text
                if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel()))
                    continue;
                widgetList.add(w);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    openHABWidgetAdapter.notifyDataSetChanged();
    if (!longPolling && isAdded()) {
        getListView().clearChoices();
        Log.d(TAG, String.format("processContent selectedItem = %d", mCurrentSelectedItem));
        if (mCurrentSelectedItem >= 0)
            getListView().setItemChecked(mCurrentSelectedItem, true);
    }
    if (getActivity() != null && mIsVisible)
        getActivity().setTitle(openHABWidgetDataSource.getTitle());
    //            }
    // Set widget list index to saved or zero position
    // This would mean we got widget and command from nfc tag, so we need to do some automatic actions!
    if (this.nfcWidgetId != null && this.nfcCommand != null) {
        Log.d(TAG, "Have widget and command, NFC action!");
        OpenHABWidget nfcWidget = this.openHABWidgetDataSource.getWidgetById(this.nfcWidgetId);
        OpenHABItem nfcItem = nfcWidget.getItem();
        // Found widget with id from nfc tag and it has an item
        if (nfcWidget != null && nfcItem != null) {
            // TODO: Perform nfc widget action here
            if (this.nfcCommand.equals("TOGGLE")) {
                //RollerShutterItem changed to RollerShutter in later builds of OH2
                if (nfcItem.getType().startsWith("Rollershutter")) {
                    if (nfcItem.getStateAsBoolean())
                        this.openHABWidgetAdapter.sendItemCommand(nfcItem, "UP");
                    else
                        this.openHABWidgetAdapter.sendItemCommand(nfcItem, "DOWN");
                } else {
                    if (nfcItem.getStateAsBoolean())
                        this.openHABWidgetAdapter.sendItemCommand(nfcItem, "OFF");
                    else
                        this.openHABWidgetAdapter.sendItemCommand(nfcItem, "ON");
                }
            } else {
                this.openHABWidgetAdapter.sendItemCommand(nfcItem, this.nfcCommand);
            }
        }
        this.nfcWidgetId = null;
        this.nfcCommand = null;
        if (this.nfcAutoClose) {
            getActivity().finish();
        }
    }

    showPage(displayPageUrl, true);
}

From source file:org.openmrs.module.hospitalcore.impl.HospitalCoreServiceImpl.java

private Set<ConceptModel> parseDiagnosis(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    Set<ConceptModel> concepts = new TreeSet<ConceptModel>();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*from w  w w . j a va 2  s .co  m*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(stream);

    NodeList rows = doc.getFirstChild().getChildNodes();
    for (int i = 0; i < rows.getLength(); i++) {
        Node row = rows.item(i);
        if (row.getNodeName().equalsIgnoreCase("row")) {
            ConceptModel cm = new ConceptModel();
            NodeList fields = row.getChildNodes();
            for (int j = 0; j < fields.getLength(); j++) {
                Node field = fields.item(j);
                NamedNodeMap attributes = field.getAttributes();
                if (field.getNodeName().equalsIgnoreCase("field")) {
                    String type = attributes.getNamedItem("name").getTextContent();
                    String value = field.getTextContent();

                    if ("name".equalsIgnoreCase(type)) {
                        cm.setName(value);
                    }

                    if ("description".equalsIgnoreCase(type)) {
                        cm.setDescription(value);
                    }
                }
            }
            concepts.add(cm);
        }
    }
    return concepts;
}

From source file:org.openmrs.module.hospitalcore.impl.HospitalCoreServiceImpl.java

private Set<Mapping> parseMapping(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    Set<Mapping> mappings = new TreeSet<Mapping>();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*from  w  ww  .j a  v  a 2 s  . co  m*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(stream);

    NodeList rows = doc.getFirstChild().getChildNodes();
    for (int i = 0; i < rows.getLength(); i++) {
        Node row = rows.item(i);
        if (row.getNodeName().equalsIgnoreCase("row")) {
            Mapping cm = new Mapping();
            NodeList fields = row.getChildNodes();
            for (int j = 0; j < fields.getLength(); j++) {
                Node field = fields.item(j);
                NamedNodeMap attributes = field.getAttributes();
                if (field.getNodeName().equalsIgnoreCase("field")) {
                    String type = attributes.getNamedItem("name").getTextContent();
                    String value = field.getTextContent();

                    if ("name".equalsIgnoreCase(type)) {
                        cm.setName(value);
                    }

                    if ("source_code".equalsIgnoreCase(type)) {
                        cm.setSourceCode(value);
                    }

                    if ("source_name".equalsIgnoreCase(type)) {
                        cm.setSource(value);
                    }
                }
            }
            mappings.add(cm);
        }
    }
    return mappings;
}

From source file:org.openmrs.module.hospitalcore.impl.HospitalCoreServiceImpl.java

private Set<Synonym> parseSynonym(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    Set<Synonym> synnonyms = new TreeSet<Synonym>();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/* www .ja v  a2  s .com*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(stream);

    NodeList rows = doc.getFirstChild().getChildNodes();
    for (int i = 0; i < rows.getLength(); i++) {
        Node row = rows.item(i);
        if (row.getNodeName().equalsIgnoreCase("row")) {
            Synonym cm = new Synonym();
            NodeList fields = row.getChildNodes();
            for (int j = 0; j < fields.getLength(); j++) {
                Node field = fields.item(j);
                NamedNodeMap attributes = field.getAttributes();
                if (field.getNodeName().equalsIgnoreCase("field")) {
                    String type = attributes.getNamedItem("name").getTextContent();
                    String value = field.getTextContent();

                    if ("concept".equalsIgnoreCase(type)) {
                        cm.setName(value);
                    }

                    if ("synonym".equalsIgnoreCase(type)) {
                        cm.setSynonym(value);
                    }
                }
            }
            synnonyms.add(cm);
        }
    }
    return synnonyms;
}

From source file:org.osaf.caldav4j.xml.OutputsDOMBase.java

public Document createNewDocument(DOMImplementation domImplementation)
        throws DOMException, DOMValidationException {
    validate();//from  ww  w .java 2 s. co  m

    Document d = domImplementation.createDocument(getNamespaceURI(), getQualifiedName(), null);

    Element root = (Element) d.getFirstChild();

    fillElement(root);

    return d;

}

From source file:org.oscarehr.common.service.myoscar.PrescriptionMedicationManager.java

private static Document toXml(Drug drug) throws ParserConfigurationException {
    Document doc = XmlUtils.newDocument("Medication");
    Node rootNode = doc.getFirstChild();

    XmlUtils.appendChildToRootIgnoreNull(doc, "Type", "PRESCRIPTION");

    // we will assume provider is the observer is the same person
    String prescriberName = MyOscarMedicalDataManagerUtils.getObserverOfDataPersonName(drug.getProviderNo());
    XmlUtils.appendChildToRootIgnoreNull(doc, "PrescriberName", prescriberName);

    XmlUtils.appendChildToRootIgnoreNull(doc, "Reason", drug.getComment());
    XmlUtils.appendChildToRootIgnoreNull(doc, "Name", drug.getDrugName());

    if (drug.getGcnSeqNo() != 0) {
        Element outterCode = doc.createElement("Code");
        rootNode.appendChild(outterCode);

        Element codingSystem = doc.createElement("CodingSystem");
        outterCode.appendChild(codingSystem);

        XmlUtils.appendChild(doc, codingSystem, "ShortDescription", "GCN_SEQNO");

        XmlUtils.appendChild(doc, outterCode, "Code", String.valueOf(drug.getGcnSeqNo()));
    }//from   ww w. ja  v a2  s. c o m

    if (drug.getAtc() != null) {
        Element outterCode = doc.createElement("Code");
        rootNode.appendChild(outterCode);

        Element codingSystem = doc.createElement("CodingSystem");
        outterCode.appendChild(codingSystem);

        XmlUtils.appendChild(doc, codingSystem, "ShortDescription", "ATC");

        XmlUtils.appendChild(doc, outterCode, "Code", drug.getAtc());
    }

    if (drug.getRegionalIdentifier() != null) {
        Element outterCode = doc.createElement("Code");
        rootNode.appendChild(outterCode);

        Element codingSystem = doc.createElement("CodingSystem");
        outterCode.appendChild(codingSystem);

        XmlUtils.appendChild(doc, codingSystem, "ShortDescription", "RegionalIdentifier");

        XmlUtils.appendChild(doc, outterCode, "Code", drug.getRegionalIdentifier());
    }

    XmlUtils.appendChildToRootIgnoreNull(doc, "Dose", drug.getDosage());
    XmlUtils.appendChildToRootIgnoreNull(doc, "Frequency", drug.getFreqCode());

    if (drug.getRoute() != null) {
        Element outterCode = doc.createElement("Route");
        rootNode.appendChild(outterCode);

        XmlUtils.appendChild(doc, outterCode, "Code", drug.getRoute());
    }

    XmlUtils.appendChildToRootIgnoreNull(doc, "Duration", drug.getDuration());

    if (drug.getDurUnit() != null) {
        Element outterCode = doc.createElement("DurationUnit");
        rootNode.appendChild(outterCode);

        XmlUtils.appendChild(doc, outterCode, "Code", drug.getDurUnit());
    }

    XmlUtils.appendChildToRootIgnoreNull(doc, "Refills", String.valueOf(drug.getRefillQuantity()));

    if (drug.getEndDate() != null) {
        Element prescriptionDuration = doc.createElement("PrescriptionDuration");
        rootNode.appendChild(prescriptionDuration);

        XmlUtils.appendChild(doc, prescriptionDuration, "EndDate",
                DateFormatUtils.ISO_DATETIME_FORMAT.format(drug.getEndDate()));
    }

    XmlUtils.appendChildToRootIgnoreNull(doc, "BrandName", drug.getBrandName());
    XmlUtils.appendChildToRootIgnoreNull(doc, "TakeMin", String.valueOf(drug.getTakeMin()));
    XmlUtils.appendChildToRootIgnoreNull(doc, "TakeMax", String.valueOf(drug.getTakeMax()));
    XmlUtils.appendChildToRootIgnoreNull(doc, "Quantity", String.valueOf(drug.getQuantity()));
    XmlUtils.appendChildToRootIgnoreNull(doc, "GenericName", drug.getGenericName());
    XmlUtils.appendChildToRootIgnoreNull(doc, "Method", drug.getMethod());
    XmlUtils.appendChildToRootIgnoreNull(doc, "DrugForm", drug.getDrugForm());
    XmlUtils.appendChildToRootIgnoreNull(doc, "LongTerm", String.valueOf(drug.getLongTerm()));
    XmlUtils.appendChildToRootIgnoreNull(doc, "PastMed", String.valueOf(drug.getPastMed()));
    XmlUtils.appendChildToRootIgnoreNull(doc, "PatientCompliance", String.valueOf(drug.getPatientCompliance()));

    return (doc);
}