Example usage for org.w3c.dom Document getXmlVersion

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

Introduction

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

Prototype

public String getXmlVersion();

Source Link

Document

An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the version number of this document.

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Create the parser
    Document xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    System.out.println(xmlDoc.getXmlVersion());

}

From source file:Main.java

/**
 * @param node//from  ww w  .jav a  2  s.  c om
 * @throws IOException
 */
public static void serializeNode(Node node) throws IOException {
    if (writer == null)
        writer = new BufferedWriter(new OutputStreamWriter(System.out));

    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        Document doc = (Document) node;
        writer.write("<?xml version=\"");
        writer.write(doc.getXmlVersion());
        writer.write("\" encoding=\"UTF-8\" standalone=\"");
        if (doc.getXmlStandalone())
            writer.write("yes");
        else
            writer.write("no");
        writer.write("\"?>\n");

        NodeList nodes = node.getChildNodes();
        if (nodes != null)
            for (int i = 0; i < nodes.getLength(); i++)
                serializeNode(nodes.item(i));
        break;
    case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        writer.write("<" + name);
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node current = attributes.item(i);
            writer.write(" " + current.getNodeName() + "=\"");
            print(current.getNodeValue());
            writer.write("\"");
        }
        writer.write(">");

        NodeList children = node.getChildNodes();
        if (children != null) {
            //if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE))
            //  writer.write("\n");

            for (int i = 0; i < children.getLength(); i++)
                serializeNode(children.item(i));
            if ((children.item(0) != null)
                    && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
                writer.write("");
        }

        writer.write("</" + name + ">");
        break;
    case Node.TEXT_NODE:
        print(node.getNodeValue());
        break;
    case Node.CDATA_SECTION_NODE:
        writer.write("CDATA");
        print(node.getNodeValue());
        writer.write("");
        break;
    case Node.COMMENT_NODE:
        writer.write("<!-- " + node.getNodeValue() + " -->\n");
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>\n");
        break;
    case Node.ENTITY_REFERENCE_NODE:
        writer.write("&" + node.getNodeName() + ";");
        break;
    case Node.DOCUMENT_TYPE_NODE:
        DocumentType docType = (DocumentType) node;
        String publicId = docType.getPublicId();
        String systemId = docType.getSystemId();
        String internalSubset = docType.getInternalSubset();
        writer.write("<!DOCTYPE " + docType.getName());
        if (publicId != null)
            writer.write(" PUBLIC \"" + publicId + "\" ");
        else
            writer.write(" SYSTEM ");
        writer.write("\"" + systemId + "\"");
        if (internalSubset != null)
            writer.write(" [" + internalSubset + "]");
        writer.write(">\n");
        break;
    }
    writer.flush();
}

From source file:Main.java

/**
 * Writes an xml representation to a stream.
 *
 * @param doc/*from w  w  w .ja  va2s.co  m*/
 *          the document
 * @param out
 *          the output stream
 * @throws IOException
 *           if there is an error transforming the dom to a stream
 */
public static void toXml(Document doc, OutputStream out) throws IOException {
    try {
        DOMSource domSource = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.VERSION, doc.getXmlVersion());
        transformer.transform(domSource, result);
    } catch (TransformerException e) {
        throw new IOException("unable to transform dom to a stream");
    }
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Find persistence units./*from w w w .  j a  v a2 s . c o  m*/
 * 
 * @param url
 *            the url
 * @param defaultTransactionType
 *            the default transaction type
 * @return the list
 * @throws Exception
 *             the exception
 */
public static List<PersistenceUnitMetadata> findPersistenceUnits(final URL url, final String[] persistenceUnits,
        PersistenceUnitTransactionType defaultTransactionType) throws InvalidConfigurationException {
    Document doc;
    try {
        doc = getDocument(url);
    } catch (InvalidConfigurationException e) {
        throw e;
    }
    doc.getXmlVersion();
    Element top = doc.getDocumentElement();

    String versionName = top.getAttribute("version");

    NodeList children = top.getChildNodes();
    ArrayList<PersistenceUnitMetadata> units = new ArrayList<PersistenceUnitMetadata>();

    // parse for persistenceUnitRootInfoURL.
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) children.item(i);
            String tag = element.getTagName();
            // look for "persistence-unit" element
            if (tag.equals("persistence-unit")) {
                PersistenceUnitMetadata metadata = parsePersistenceUnit(url, persistenceUnits, element,
                        versionName);
                if (metadata != null) {
                    units.add(metadata);
                }
            }
        }
    }
    return units;
}

From source file:channellistmaker.listmaker.XMLLoaderTest.java

/**
 * Test of Load method, of class XMLLoader.
 *//*from   w  w w.  jav a 2 s .c  o  m*/
@Test
public void testLoad() {
    LOG.info("");
    File F = new File("./test/101.xml");
    XMLLoader instance = target;
    Document result = instance.Load(F);
    assertEquals("1.0", result.getXmlVersion());
}

From source file:com.photon.maven.plugins.android.standalonemojos.ManifestUpdateMojo.java

/**
 * Write manifest using JAXP transformer
 *//*w  w  w . java 2 s .c o m*/
private void writeManifest(File manifestFile, Document doc) throws IOException, TransformerException {
    TransformerFactory xfactory = TransformerFactory.newInstance();
    Transformer xformer = xfactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(doc);

    FileWriter writer = null;
    try {
        writer = new FileWriter(manifestFile, false);
        String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(),
                doc.getXmlEncoding());
        writer.write(xmldecl);
        Result result = new StreamResult(writer);

        xformer.transform(source, result);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.java

/**
 * Copy the AndroidManifest.xml from androidManifestFile to destinationManifestFile
 *
 * @throws MojoExecutionException//from w  w  w . j a va 2 s . c  o m
 */
protected void copyManifest() throws MojoExecutionException {
    getLog().debug("copyManifest: " + androidManifestFile + " -> " + destinationManifestFile);
    if (androidManifestFile == null) {
        getLog().debug("Manifest copying disabled. Using default manifest only");
        return;
    }

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(androidManifestFile);
        Source source = new DOMSource(doc);

        TransformerFactory xfactory = TransformerFactory.newInstance();
        Transformer xformer = xfactory.newTransformer();
        xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        FileWriter writer = null;
        try {
            destinationManifestFile.getParentFile().mkdirs();

            writer = new FileWriter(destinationManifestFile, false);
            if (doc.getXmlEncoding() != null && doc.getXmlVersion() != null) {
                String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(),
                        doc.getXmlEncoding());

                writer.write(xmldecl);
            }
            Result result = new StreamResult(writer);
            xformer.transform(source, result);
            getLog().info("Manifest copied from " + androidManifestFile + " to " + destinationManifestFile);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    } catch (Exception e) {
        getLog().error("Error during copyManifest");
        throw new MojoExecutionException("Error during copyManifest", e);
    }
}

From source file:com.panet.imeta.job.entries.dtdvalidator.JobEntryDTDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//  www  .  j a v a 2 s .  c o m

    String realxmlfilename = getRealxmlfilename();
    String realDTDfilename = getRealDTDfilename();

    FileObject xmlfile = null;
    FileObject DTDfile = null;

    try

    {

        if (xmlfilename != null && ((dtdfilename != null && !dtdintern) || (dtdintern))) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);

            if (xmlfile.exists())

            {

                //URL xmlFile = new URL (KettleVFS.getFilename(xmlfile));
                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();

                // open XML File
                BufferedReader xmlBufferedReader = new BufferedReader(
                        new InputStreamReader(xmlFile.openStream()));
                StringBuffer xmlStringbuffer = new StringBuffer("");

                char[] buffertXML = new char[1024];
                int LenXML = -1;
                while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1)
                    xmlStringbuffer.append(buffertXML, 0, LenXML);

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                Document xmlDocDTD = null;
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding
                DocBuilderFactory.setValidating(false);
                xmlDocDTD = DocBuilder
                        .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")));

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (dtdintern) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename));
                    } else {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(realDTDfilename);

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            //String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");

                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        realDTDfilename));
                    }
                }

                if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists()))) {
                    result.setResult(false);
                    result.setNrErrors(1);
                } else {
                    DocBuilderFactory.setValidating(true);

                    // Let's parse now ...

                    xmlDocDTD = DocBuilder
                            .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)));
                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label",
                                        realxmlfilename));

                    // Everything is OK
                    result.setResult(true);
                }

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename));
                }

                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {
        log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"),
                Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label", realxmlfilename,
                        realDTDfilename, e.getMessage()));

        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (DTDfile != null)
                DTDfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:org.pentaho.di.job.entries.dtdvalidator.DTDValidator.java

public boolean validate() {

    boolean retval = false;

    FileObject xmlfile = null;/* w  w  w. ja  v a 2s  .  co  m*/
    FileObject DTDfile = null;

    ByteArrayInputStream ba = null;
    try {
        if (xmlfilename != null && ((getDTDFilename() != null && !isInternDTD()) || (isInternDTD()))) {
            xmlfile = KettleVFS.getFileObject(getXMLFilename());

            if (xmlfile.exists()) {

                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();
                StringBuffer xmlStringbuffer = new StringBuffer("");

                BufferedReader xmlBufferedReader = null;
                InputStreamReader is = null;
                try {
                    // open XML File
                    is = new InputStreamReader(xmlFile.openStream());
                    xmlBufferedReader = new BufferedReader(is);

                    char[] buffertXML = new char[1024];
                    int LenXML = -1;
                    while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) {
                        xmlStringbuffer.append(buffertXML, 0, LenXML);
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (xmlBufferedReader != null) {
                        xmlBufferedReader.close();
                    }
                }

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding

                DocBuilderFactory.setValidating(false);
                ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8"));
                Document xmlDocDTD = DocBuilder.parse(ba);
                if (ba != null) {
                    ba.close();
                }

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (isInternDTD()) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFound.Label",
                                getXMLFilename()));
                    } else {
                        setErrorMessage(BaseMessages.getString(PKG,
                                "JobEntryDTDValidator.ERRORDTDNotFound.Label", getXMLFilename()));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(getDTDFilename());

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            // String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");
                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(
                                BaseMessages.getString(PKG,
                                        "JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        getDTDFilename()));
                    }
                }

                if (!(isInternDTD() && xmlStartDTD == -1 || (!isInternDTD() && !DTDfile.exists()))) {

                    // Let's parse now ...
                    MyErrorHandler error = new MyErrorHandler();
                    DocBuilderFactory.setValidating(true);
                    DocBuilder = DocBuilderFactory.newDocumentBuilder();
                    DocBuilder.setErrorHandler(error);

                    ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding));
                    xmlDocDTD = DocBuilder.parse(ba);

                    if (error.errorMessage == null) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Label",
                                        getXMLFilename()));

                        // Everything is OK
                        retval = true;
                    } else {
                        // Invalid DTD
                        setNrErrors(error.nrErrors);
                        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorKO",
                                getXMLFilename(), error.nrErrors, error.errorMessage));
                    }
                }

            } else {
                if (!xmlfile.exists()) {
                    setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.FileDoesNotExist.Label",
                            getXMLFilename()));
                }
            }
        } else {
            setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.AllFilesNotNull.Label"));
        }
    } catch (Exception e) {
        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.ErrorDTDValidator.Label",
                getXMLFilename(), getDTDFilename(), e.getMessage()));
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }
            if (DTDfile != null) {
                DTDfile.close();
            }
            if (ba != null) {
                ba.close();
            }
        } catch (IOException e) {
            // Ignore close errors
        }
    }
    return retval;
}

From source file:org.sakaiproject.myshowcase.tool.MyShowcaseGetShowcaseEvidenceMappingsController.java

private void getCompetencyList() {

    try {/* w w w .  j a va2 s .c  o m*/

        WebServiceConsumer wsc = new WebServiceConsumer();

        String studentId = "d289a01d-7cee-4569-a6c3-1a0a8e414582";

        String orgGroupId = "192";

        wsc.setURL("http://www.learning-slate.com/multiport/services/services.asmx");

        wsc.setWebService("Competency");

        wsc.clear();

        wsc.setWebMethod("GetCompetenciesForStudent");

        wsc.add(new Parameter("studentId", studentId));

        System.out.println("Full results :\n" + wsc.getResults().toString());

        Document dom = wsc.getXMLResults();

        System.out.println("Version : " + dom.getXmlVersion().toString());

        Element docEle = dom.getDocumentElement();

        NodeList nl = docEle.getElementsByTagName("competency");

        if (nl != null && nl.getLength() > 0) {

            System.out.println("Found some : " + nl.getLength());

            for (int i = 0; i < nl.getLength(); i++) {

                Element el = (Element) nl.item(i);

                System.out.println("Attribute : " + el.getAttribute("id").toString());

                System.out.println("Attribute : " + el.getAttribute("label").toString());

                competencyList.add(
                        new Parameter(el.getAttribute("id").toString(), el.getAttribute("label").toString()));
            }
        }

    } catch (Exception e) {

        System.out.println(e.toString());
    }
}