Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:XMLConfig.java

/** Creates an empty configuration.
 *///ww w  . j av  a2 s.c o  m
public XMLConfig() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        _document = builder.newDocument(); // Create from whole cloth
        // NOTE: not 1.4 compatible -- _document.setXmlStandalone(true);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:me.cavar.pg2tei.TEIDoc.java

/**
 *
 * @return Document//w  w w  . j a  va2 s .  co m
 * @throws ParserConfigurationException
 */
public void genTEIXMLDom() {
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        this.mydom = docBuilder.newDocument();

        // TEI root element
        Element root = this.mydom.createElement("TEI");
        root.setAttribute("xmlns", "http://www.tei-c.org/ns/1.0");
        this.mydom.appendChild(root);
        this.mydom.insertBefore(this.mydom.createProcessingInstruction("xml-model",
                "href=\"http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/teilite.rng\""
                        + " schematypens=\"http://relaxng.org/ns/structure/1.0\""),
                root);

        // create teiHeader section
        Element teiHeader = this.mydom.createElement("teiHeader");
        root.appendChild(teiHeader);

        // create fileDescription section
        Element fileDesc = this.mydom.createElement("fileDesc");
        teiHeader.appendChild(fileDesc);

        // create titleStmt
        Element titleStmt = this.mydom.createElement("titleStmt");
        // check for multi-line titles
        Element ltmp;
        Element tmp = this.mydom.createElement("title");
        tmp.setAttribute("type", "full");
        int numTitles = this.title.size();
        if (numTitles > 0) {
            String tmpStr = this.title.get(numTitles - 1);
            if (tmpStr.contains("\n")) {
                // make multiple title statements
                String[] subStrs = tmpStr.split("\n");

                // the first one is main
                ltmp = this.mydom.createElement("title");
                ltmp.setAttribute("type", "main");
                ltmp.appendChild(this.mydom.createTextNode(subStrs[0]));
                tmp.appendChild(ltmp);

                // TODO
                // all others are sub should not be... but...
                for (int i = 1; i < subStrs.length; i++) {
                    ltmp = this.mydom.createElement("title");
                    ltmp.setAttribute("type", "sub");
                    ltmp.appendChild(this.mydom.createTextNode(subStrs[i]));
                    tmp.appendChild(ltmp);
                }
                // titleStmt.appendChild(tmp);
            } else { // make single title statement
                ltmp = this.mydom.createElement("title");
                ltmp.setAttribute("type", "main");
                ltmp.appendChild(this.mydom.createTextNode(this.title.get(numTitles - 1)));
                tmp.appendChild(ltmp);
            }
        }
        ltmp = this.mydom.createElement("title");
        ltmp.setAttribute("type", "alt");
        ltmp.appendChild(this.mydom.createTextNode(this.friendlyTitle));
        tmp.appendChild(ltmp);
        titleStmt.appendChild(tmp);

        // add author information
        tmp = this.mydom.createElement("author");
        if (this.creator != null) {
            // split year of from author string
            Pattern nameSplitRE = Pattern
                    .compile("(?<name>[\\w,\\s]+)(?<year>,\\s+\\d\\d\\d\\d\\s?-+\\s?\\d\\d\\d\\d)");
            Matcher matcher = nameSplitRE.matcher(this.creator);
            if (matcher.find(0)) {
                String tmpN = matcher.group("name");
                //String tmpY = matcher.group("year");
                tmp.appendChild(this.mydom.createTextNode(tmpN));
            } else {
                tmp.appendChild(this.mydom.createTextNode(this.creator));
            }
        }
        titleStmt.appendChild(tmp);
        fileDesc.appendChild(titleStmt);

        // publicationStmt in fileDesc
        Element publicationStmt = this.mydom.createElement("publicationStmt");
        tmp = this.mydom.createElement("publisher");
        if (this.publisher != null) {
            tmp.appendChild(this.mydom.createTextNode(this.publisher));
        }
        publicationStmt.appendChild(tmp);
        // date
        tmp = this.mydom.createElement("date");
        if (this.createdW3CDTF != null) {
            tmp.appendChild(this.mydom.createTextNode(this.createdW3CDTF));
        }
        publicationStmt.appendChild(tmp);
        // availability
        tmp = this.mydom.createElement("availability");
        ltmp = this.mydom.createElement("licence");
        for (String right : this.rights) {
            Element ptmp = this.mydom.createElement("p");
            ptmp.appendChild(this.mydom.createTextNode(right));
            ltmp.appendChild(ptmp);
        }
        tmp.appendChild(ltmp);
        publicationStmt.appendChild(tmp);
        // distributor
        tmp = this.mydom.createElement("distributor");
        // tmp.appendChild(doc.createTextNode("Distributed in the TEI XML format by:"));
        Element ptmp;
        ptmp = this.mydom.createElement("name");
        ptmp.setAttribute("xml:id", "DC");
        ptmp.appendChild(this.mydom.createTextNode("Damir Cavar"));
        tmp.appendChild(ptmp);
        ptmp = this.mydom.createElement("name");
        ptmp.setAttribute("xml:id", "LTL");
        ptmp.appendChild(this.mydom.createTextNode("Language Technology Lab"));
        tmp.appendChild(ptmp);
        ptmp = this.mydom.createElement("name");
        ptmp.setAttribute("xml:id", "ILIT");
        ptmp.appendChild(this.mydom.createTextNode("Institute for Language Information and Technology"));
        tmp.appendChild(ptmp);
        ptmp = this.mydom.createElement("name");
        ptmp.setAttribute("xml:id", "EMU");
        ptmp.appendChild(this.mydom.createTextNode("Eastern Michigan University"));
        tmp.appendChild(ptmp);

        ltmp = this.mydom.createElement("address");
        // add address info
        ptmp = this.mydom.createElement("addrLine");
        ptmp.appendChild(this.mydom.createTextNode("2000 E. Huron River Dr., Suite 104"));
        ltmp.appendChild(ptmp);
        ptmp = this.mydom.createElement("addrLine");
        ptmp.appendChild(this.mydom.createTextNode("Ypsilanti, MI 48197"));
        ltmp.appendChild(ptmp);
        ptmp = this.mydom.createElement("addrLine");
        ptmp.appendChild(this.mydom.createTextNode("USA"));
        ltmp.appendChild(ptmp);
        tmp.appendChild(ltmp);
        publicationStmt.appendChild(tmp);
        // idno
        tmp = this.mydom.createElement("idno");
        if (this.id != null) {
            tmp.appendChild(this.mydom.createTextNode(Integer.toString(this.idN)));
        }
        publicationStmt.appendChild(tmp);
        fileDesc.appendChild(publicationStmt);

        // --------------------------------------------
        // sourceDesc in fileDesc
        Element sourceDesc = this.mydom.createElement("sourceDesc");
        // contains a <p> with a description of the source
        tmp = this.mydom.createElement("p");
        tmp.appendChild(this.mydom.createTextNode("This text was automatically "
                + "converted from the corresponding HTML formated text found in the "
                + "Project Gutenberg (http://www.gutenberg.org/) collection."));
        sourceDesc.appendChild(tmp);
        if (this.creator != null) {
            tmp = this.mydom.createElement("p");
            tmp.appendChild(this.mydom.createTextNode("Creator: " + this.creator));
            sourceDesc.appendChild(tmp);
        }
        if (this.description != null) {
            tmp = this.mydom.createElement("p");
            tmp.appendChild(this.mydom.createTextNode(this.description));
            sourceDesc.appendChild(tmp);
        }
        fileDesc.appendChild(sourceDesc);

        // --------------------------------------------
        // encodingDesc in teiHeader
        Element encodingDesc = this.mydom.createElement("encodingDesc");
        // contains a appInfo with a description of the source
        tmp = this.mydom.createElement("appInfo");
        // appInfo contains application
        ltmp = this.mydom.createElement("application");
        ltmp.setAttribute("ident", "gutenberg2tei");
        ltmp.setAttribute("version", "1.0");
        ptmp = this.mydom.createElement("desc");
        ptmp.appendChild(
                this.mydom.createTextNode("Conversion tool using the RDF file catalog and meta-information "
                        + "and conversion of HTML to TEI XML."));
        ltmp.appendChild(ptmp);
        tmp.appendChild(ltmp);
        encodingDesc.appendChild(tmp);
        // contains projectDesc
        tmp = this.mydom.createElement("projectDesc");
        ltmp = this.mydom.createElement("p");
        ltmp.appendChild(this.mydom.createTextNode("The conversion of the Project Gutenberg "
                + "texts to the TEI XML format started as an independent project at ILIT, EMU."));
        tmp.appendChild(ltmp);
        encodingDesc.appendChild(tmp);
        // contains samplingDecl
        tmp = this.mydom.createElement("samplingDecl");
        ltmp = this.mydom.createElement("p");
        ltmp.appendChild(this.mydom.createTextNode(""));
        tmp.appendChild(ltmp);
        encodingDesc.appendChild(tmp);
        // classDecl
        tmp = this.mydom.createElement("classDecl");
        ltmp = this.mydom.createElement("taxonomy");
        ltmp.setAttribute("xml:id", "lcsh");
        ptmp = this.mydom.createElement("bibl");
        ptmp.appendChild(this.mydom.createTextNode("Library of Congress Subject Headings"));
        ltmp.appendChild(ptmp);
        tmp.appendChild(ltmp);
        ltmp = this.mydom.createElement("taxonomy");
        ltmp.setAttribute("xml:id", "lc");
        ptmp = this.mydom.createElement("bibl");
        ptmp.appendChild(this.mydom.createTextNode("Library of Congress Classification"));
        ltmp.appendChild(ptmp);
        tmp.appendChild(ltmp);
        ltmp = this.mydom.createElement("taxonomy");
        ltmp.setAttribute("xml:id", "pg");
        ptmp = this.mydom.createElement("bibl");
        ptmp.appendChild(this.mydom.createTextNode("Project Gutenberg Category"));
        ltmp.appendChild(ptmp);
        tmp.appendChild(ltmp);
        encodingDesc.appendChild(tmp);

        teiHeader.appendChild(encodingDesc);

        // --------------------------------------------
        // profileDesc in teiHeader
        Element profileDesc = this.mydom.createElement("profileDesc");
        // contains creation contains date
        tmp = this.mydom.createElement("creation");
        ltmp = this.mydom.createElement("date");
        ltmp.appendChild(this.mydom.createTextNode(this.createdW3CDTF));
        tmp.appendChild(ltmp);
        // add the author name here too, although not correct...
        //ltmp = doc.createElement("name");
        //ltmp.appendChild(doc.createTextNode(this.creator));
        //tmp.appendChild(ltmp);
        profileDesc.appendChild(tmp);
        // contains langUsage
        if (this.languageCode != null) {
            tmp = this.mydom.createElement("langUsage");
            ltmp = this.mydom.createElement("language");
            ltmp.setAttribute("ident", this.languageCode);
            Locale aLocale = Locale.forLanguageTag(this.languageCode);
            ltmp.appendChild(this.mydom.createTextNode(aLocale.getDisplayLanguage() + "."));
            tmp.appendChild(ltmp);
            profileDesc.appendChild(tmp);
        }
        // textClass
        tmp = this.mydom.createElement("textClass");
        ltmp = this.mydom.createElement("keywords");
        ltmp.setAttribute("scheme", "#lcsh");
        if (this.subjectHeadingsLCC.size() > 0) {
            for (String term : this.subjectHeadingsLCC) {
                ptmp = this.mydom.createElement("term");
                ptmp.appendChild(this.mydom.createTextNode(term));
                ltmp.appendChild(ptmp);
            }
        } else {
            ptmp = this.mydom.createElement("term");
            // ptmp.appendChild(doc.createTextNode(term));
            ltmp.appendChild(ptmp);
        }
        tmp.appendChild(ltmp);
        if (this.classificationLCC != null) {
            ltmp = this.mydom.createElement("classCode");
            ltmp.setAttribute("scheme", "#lc");
            ltmp.appendChild(this.mydom.createTextNode(this.classificationLCC));
            tmp.appendChild(ltmp);
        }
        if (this.projGCategory != null) {
            ltmp = this.mydom.createElement("classCode");
            ltmp.setAttribute("scheme", "#pg");
            ltmp.appendChild(this.mydom.createTextNode(this.projGCategory));
            tmp.appendChild(ltmp);
        }
        profileDesc.appendChild(tmp);
        teiHeader.appendChild(profileDesc);

        // --------------------------------------------
        // revisionDesc in teiHeader
        Element revisionDesc = this.mydom.createElement("revisionDesc");
        // contains a list of change tags
        tmp = this.mydom.createElement("change");
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date t = new Date();
        tmp.setAttribute("when", ft.format(t));
        tmp.setAttribute("who", "#DC");
        tmp.appendChild(this.mydom.createTextNode("Initial conversion from HTML to TEI XML."));
        revisionDesc.appendChild(tmp);
        teiHeader.appendChild(revisionDesc);
        // create text section
        // Element text = this.mydom.createElement("text");
        // !!!
        // skip that and just append the text-Element from the converted HTML-document.
        // !!!
        // root.appendChild(text);
    } catch (ParserConfigurationException e) {
        Logger.getLogger(Fetcher.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.iontorrent.vaadin.utils.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        res = new ApplicationResource() {

            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();
                    info = new ChartRenderingInfo();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*www.j  a  v a 2 s. c o m*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator

                        chart.draw(svgGenerator, new Rectangle(widht, height), info);
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {

                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            public Application getApplication() {
                return JFreeChartWrapper.this.getApplication();
            }

            public int getBufferSize() {
                if (getByteStream() != null) {
                    return getByteStream().available();
                } else {
                    return 0;
                }
            }

            public long getCacheTime() {
                return 0;
            }

            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return "graph.png";
                } else {
                    return gzipEnabled ? "graph.svgz" : "graph.svg";
                }
            }

            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getByteStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.photon.phresco.util.ProjectUtils.java

private void addWebLogicPlugin(File pomFile, String pluginVersion) throws PhrescoException {
    try {//w w w .  j  a  v  a2  s  . com
        PomProcessor pomProcessor = new PomProcessor(pomFile);
        pomProcessor.addPlugin("com.oracle.weblogic", "weblogic-maven-plugin", pluginVersion);
        List<Element> configList = new ArrayList<Element>();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element adminUrl = doc.createElement("adminurl");
        adminUrl.setTextContent("t3://${server.host}:${server.port}");
        Element user = doc.createElement("user");
        user.setTextContent("${server.username}");
        Element password = doc.createElement("password");
        password.setTextContent("${server.password}");
        Element upload = doc.createElement("upload");
        upload.setTextContent("true");
        Element action = doc.createElement("action");
        action.setTextContent("deploy");
        Element remote = doc.createElement("remote");
        remote.setTextContent("true");
        Element verbose = doc.createElement("verbose");
        verbose.setTextContent("false");
        Element source = doc.createElement("source");
        source.setTextContent("${project.basedir}/do_not_checkin/build/temp/${project.build.finalName}.war");
        Element name = doc.createElement("name");
        name.setTextContent("${project.build.finalName}");
        Element argLineElem = doc.createElement("argLine");
        argLineElem.setTextContent("-Xmx512m");

        configList.add(adminUrl);
        configList.add(user);
        configList.add(password);
        configList.add(upload);
        configList.add(action);
        configList.add(remote);
        configList.add(verbose);
        configList.add(source);
        configList.add(name);
        configList.add(argLineElem);

        pomProcessor.addConfiguration("com.oracle.weblogic", "weblogic-maven-plugin", configList);
        pomProcessor.save();

    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (PhrescoPomException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.vaadin.addon.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*from www.j  av  a 2s.  co m*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(widht, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final List<Element> createEntityFromBusinessObject(final BusinessEntity businessEntity)
        throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    if (businessEntity != null) {
        final Node node = businessEntity.getDomNode();
        if (node.hasChildNodes()) {
            final NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* To avoid : 'DOM Level 3 Not implemented' error */
                final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                final Document document = builder.newDocument();
                final Element element = (Element) document.importNode(nodeList.item(i), true);

                if (element.getNodeName() != null && element.getNodeName().contains(":")) {
                    final String nodeName = element.getNodeName().split(":")[1];

                    /* Check for attributes */
                    final NamedNodeMap attributes = element.getAttributes();

                    if (attributes != null && attributes.getLength() != 0) {

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        for (int j = 0; j < attributes.getLength(); j++) {
                            final Attr attr = (Attr) attributes.item(j);

                            /* Set node name and value in map */
                            attributeMap.put(attr.getNodeName(), attr.getNodeValue());
                        }//from  www .  ja  va 2s  .  c  om

                        /* Create node with attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent(), attributeMap));
                    } else {

                        /* Create node without attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent()));
                    }
                }
            }
        }
        return elementList;
    } else {
        return null;
    }
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Constructs a new application context generator.
 *
 * @param springVersion the Spring version
 * @param defaultScope// w  ww .  ja v  a2s  . c  o m
 */
public ReflectionApplicationContextGenerator(String springVersion, String defaultScope) {
    //create the XML document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = dbfac.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        //never thrown in my case, so ignore it
    }
    document = docBuilder.newDocument();

    //create the root element
    root = document.createElementNS("http://www.springframework.org/schema/beans", "beans");
    root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation",
            "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-"
                    + springVersion + ".xsd");
    document.appendChild(root);
    this.defaultScope = defaultScope;
}

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private Document createDocument(DocumentBuilderFactory dbf) {
    Document dom;/*from  w ww.  j  av a 2s .c  o  m*/
    try {
        //Create Document
        DocumentBuilder db = dbf.newDocumentBuilder();
        dom = db.newDocument();
        return dom;
    } catch (ParserConfigurationException e) {
        //         LOG.info("Error instantiating DocumentBuilder " + e);
    }
    return null;
}

From source file:com.netspective.sparx.form.DialogContext.java

public Document getAsXmlDocument() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element root = doc.createElement("sparx");
    doc.appendChild(root);//from  w ww  .  ja  v a 2s .c  o m

    exportToXml(doc.getDocumentElement());
    return doc;
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

/**
 * //from w w  w  . j  av  a  2  s. co  m
 * @param entity
 * @return
 * @throws Exception
 */
public static final List<Element> createV5EntityFromBusinessObject(final Entity entity) throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    /* Set entity id */
    elementList.add(createMessageElement("id", entity.getId()));

    /* Step 2: get all node attributes */
    final AttributeCollection attCol = entity.getAttributes();

    /* Check if entity is not null */
    if (attCol != null) {

        /* Get all attributes for the CRM field */
        final KeyValuePairOfstringanyType[] kvpsatArr = attCol.getKeyValuePairOfstringanyTypeArray();

        /* This is to avoid : 'DOM Level 3 Not implemented' error */
        final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document document = builder.newDocument();

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside createV5EntityFromBusinessObject: no of crm fields: " + kvpsatArr.length);
        }

        /* Iterate over all attributes */
        for (final KeyValuePairOfstringanyType kvpsat : kvpsatArr) {

            /* Get field name */
            final String fieldName = kvpsat.getKey();

            if (logger.isDebugEnabled()) {
                logger.debug("----Inside createV5EntityFromBusinessObject: crm field name: " + fieldName);
            }

            /* Get field value */
            String fieldValue = null;

            /* Get field value node */
            final XmlObject xo = kvpsat.getValue();

            /* If object is valid */
            if (xo != null) {

                /* Get DOM node from Xo */
                final Node node = xo.getDomNode();

                /* Check if node is not null */
                if (node != null && node.hasChildNodes()) {

                    /* Get all child nodes */
                    final NodeList nodeList = node.getChildNodes();

                    /* Create new map for attributes */
                    final Map<String, String> attributeMap = new HashMap<String, String>();

                    /* If more than 1 elements in node list */
                    if (nodeList.getLength() > 1) {

                        /* Iterate on all child node list */
                        for (int i = 0; i < nodeList.getLength(); i++) {

                            if (nodeList.item(i) instanceof Element) {

                                final Element childElement = (Element) document.importNode(nodeList.item(i),
                                        true);

                                if (childElement.getNodeName() != null
                                        && childElement.getNodeName().contains(":")) {

                                    /* Get attribute name */
                                    final String attName = childElement.getNodeName().split(":")[1];

                                    /* Get attribute value */
                                    final String attValue = childElement.getTextContent();

                                    if ("id".equalsIgnoreCase(attName)) {

                                        fieldValue = attValue;
                                    } else {

                                        /* Put values in map */
                                        attributeMap.put(attName, attValue);
                                    }
                                }
                            }
                        }

                        /* Create node with attributes */
                        elementList.add(createMessageElement(fieldName, fieldValue, attributeMap));

                    } else if (nodeList.getLength() == 1) {

                        /* Iterate on all child node list */
                        if (nodeList.item(0) instanceof Element) {

                            final Element childElement = (Element) document.importNode(nodeList.item(0), true);

                            /* Get attribute value */
                            fieldValue = childElement.getTextContent();

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, fieldValue));
                        } else {

                            /* Create node with attributes */
                            elementList.add(createMessageElement(fieldName, nodeList.item(0).getNodeValue()));
                        }
                    }
                } else {

                    /* Create node with attributes */
                    elementList.add(createMessageElement(fieldName, node.getTextContent()));
                }
            }
        }
    }

    return elementList;
}