Example usage for org.w3c.dom Element getAttribute

List of usage examples for org.w3c.dom Element getAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttribute.

Prototype

public String getAttribute(String name);

Source Link

Document

Retrieves an attribute value by name.

Usage

From source file:com.valco.utility.FacturasUtility.java

public static void agregarDatosDeTimbrado(Facturas factura, String xml)
        throws ParserConfigurationException, SAXException, IOException, ParseException {
    String folioFiscal = null;/*w w  w .ja  va2 s .c  o m*/
    Date fechaTimbrado = new Date();
    String selloCFD = null;
    String noCertificadoSat = null;
    String selloSat = null;
    SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputStream inputXml = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    org.w3c.dom.Document doc = dBuilder.parse(inputXml);
    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName("tfd:TimbreFiscalDigital");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            folioFiscal = eElement.getAttribute("UUID");
            fechaTimbrado = formatDate.parse(eElement.getAttribute("FechaTimbrado"));
            selloCFD = eElement.getAttribute("selloCFD");
            noCertificadoSat = eElement.getAttribute("noCertificadoSAT");
            selloSat = eElement.getAttribute("selloSAT");

            factura.setFolioFiscal(folioFiscal);
            factura.setFechaTimbrado(fechaTimbrado);
            factura.setSelloCdfi(selloCFD);
            factura.setNoSerieCertSat(noCertificadoSat);
            factura.setSelloSat(selloSat);
        }
    }
}

From source file:importer.handler.post.stages.Discriminator.java

/**
 * Add a new version to the current element
 * @param elem the element to add the new version to
 * @param wits the new version//from   w  w  w.j  a  v a 2s .  c  om
 */
static void addVersion(Element elem, String wits) {
    if (elem.hasAttribute(Splitter.VERSIONS))
        elem.setAttribute(Splitter.VERSIONS, mergeVersions(elem.getAttribute(Splitter.VERSIONS), wits));
    else
        elem.setAttribute(Splitter.VERSIONS, wits);
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets a set of names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @param configFilePath file path of checkstyle_checks.xml.
 * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *///w w  w . jav  a2 s .co  m
private static Set<String> getCheckStyleChecksReferencedInConfig(String configFilePath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.parse(new File(configFilePath));

    // optional, but recommended
    // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    document.getDocumentElement().normalize();

    final NodeList nodeList = document.getElementsByTagName("module");

    Set<String> checksReferencedInCheckstyleChecksXML = new HashSet<>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            final Element module = (Element) currentNode;
            final String checkName = module.getAttribute("name");
            if (!"Checker".equals(checkName) && !"TreeWalker".equals(checkName)
                    && !"SuppressionFilter".equals(checkName)) {
                checksReferencedInCheckstyleChecksXML.add(checkName);
            }
        }
    }
    return checksReferencedInCheckstyleChecksXML;
}

From source file:Main.java

/**
 * Resolves the xpath of an element.//from w ww  . j  av a2s .  com
 * 
 * @param elt
 * @return
 * @throws IOException
 */
public static final String getElementXPath(Node elt) throws IOException {
    String path = "";

    Node currentNode = elt;
    while (!(currentNode instanceof Document)) {
        Element parent = (Element) currentNode;
        if (!parent.getTagName().equals("schema")) {
            if (!parentNodeHasMoreOfThese((Element) currentNode)) {
                path = '/' + parent.getTagName() + path;
            } else {
                path = '/' + parent.getTagName() + '[' + getElementIdx(parent) + ']' + path;
            }
        } else {
            String schema = parent.getAttribute("name");
            String[] segments = path.substring(1).split(":", 2);
            return schema + ':' + segments[segments.length - 1];
        }

        currentNode = currentNode.getParentNode();
    }

    throw new IOException("Failed to parse document.");
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets names of checkstyle's modules which are documented in xdocs.
 * @param xdocsDirectoryPath xdocs directory path.
 * @return a set of checkstyle's modules which have xdoc documentation.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *///  ww  w .j av a 2 s . c  om
private static Set<String> getModulesNamesWhichHaveXdoc(String xdocsDirectoryPath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final Set<Path> xdocsFilePaths = getXdocsFilePaths(xdocsDirectoryPath);
    final Set<String> modulesNamesWhichHaveXdoc = new HashSet<>();

    for (Path path : xdocsFilePaths) {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(path.toFile());

        // optional, but recommended
        // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        final NodeList nodeList = document.getElementsByTagName("section");

        for (int i = 0; i < nodeList.getLength(); i++) {
            final Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                final Element module = (Element) currentNode;
                final String moduleName = module.getAttribute("name");
                if (!"Content".equals(moduleName) && !"Overview".equals(moduleName)) {
                    modulesNamesWhichHaveXdoc.add(moduleName);
                }
            }
        }
    }
    return modulesNamesWhichHaveXdoc;
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void parseXML(String s) {
    try {/*from   w w  w . ja  v  a  2 s .  co m*/

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(s));

        Document document = documentBuilder.parse(inputSource);
        NodeList nodes = document.getElementsByTagName("virtual-sensor");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            String sensor_name = element.getAttribute("name");

            if (!sensorsUpdateDelay.containsKey(sensor_name))
                continue; // skip sensors that are not monitored

            logger.warn("Sensor: " + sensor_name);

            NodeList listOfField = element.getElementsByTagName("field");
            for (int j = 0; j < listOfField.getLength(); j++) {
                Element line = (Element) listOfField.item(j);

                if (line.getAttribute("name").indexOf("timed") >= 0) {
                    String last_updated_as_string = line.getTextContent();

                    try {
                        Long last_updated_as_Long = GregorianCalendar.getInstance().getTimeInMillis()
                                - VSensorMonitorConfig.datetime2timestamp(last_updated_as_string);
                        logger.warn(new StringBuilder(last_updated_as_string).append(" => ")
                                .append(VSensorMonitorConfig.ms2dhms(last_updated_as_Long)).toString());

                        sensorsUpdateDelay.put(sensor_name, last_updated_as_Long);
                    } catch (ParseException e) {
                        errorsBuffer.append("Last update time for sensor ").append(sensor_name)
                                .append(" cannot be read. Error while parsing > ")
                                .append(last_updated_as_string).append(" <\n");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Exception while parsing XML\n");
        e.printStackTrace();
    }
}

From source file:com.omertron.yamjtrakttv.tools.CompleteMoviesTools.java

/**
 * Get the season and episode information from the files section for TV
 * Shows/*from w w w .  jav a 2s . com*/
 *
 * @param eVideo
 * @return
 */
private static List<Episode> parseTvFiles(Element eVideo) {
    List<Episode> episodes = new ArrayList<>();

    NodeList nlFile = eVideo.getElementsByTagName("file");
    if (nlFile.getLength() > 0) {
        Node nFile;
        Element eFile;
        for (int loop = 0; loop < nlFile.getLength(); loop++) {
            nFile = nlFile.item(loop);
            if (nFile.getNodeType() == Node.ELEMENT_NODE) {
                eFile = (Element) nFile;
                int season = Integer.parseInt(DOMHelper.getValueFromElement(eFile, "season"));
                int firstPart = Integer.parseInt(eFile.getAttribute("firstPart"));
                int lastPart = Integer.parseInt(eFile.getAttribute("lastPart"));
                boolean watched = Boolean.parseBoolean(DOMHelper.getValueFromElement(eFile, "watched"));
                Date watchedDate;

                String stringDate = DOMHelper.getValueFromElement(eVideo, "watchedDate");
                if (StringUtils.isNumeric(stringDate)) {
                    watchedDate = new Date(Long.parseLong(stringDate));
                } else {
                    watchedDate = new Date();
                }

                for (int episode = firstPart; episode <= lastPart; episode++) {
                    episodes.add(new Episode(season, episode, watched, watchedDate));
                }
            }
        }
    }
    return episodes;
}

From source file:com.msopentech.odatajclient.engine.data.atom.AtomDeserializer.java

public static AtomEntry entry(final Element input) {
    if (!ODataConstants.ATOM_ELEM_ENTRY.equals(input.getNodeName())) {
        return null;
    }/*from ww w  .  j  a  v a 2  s . com*/

    final AtomEntry entry = new AtomEntry();

    common(input, entry);

    final String etag = input.getAttribute(ODataConstants.ATOM_ATTR_ETAG);
    if (StringUtils.isNotBlank(etag)) {
        entry.setETag(etag);
    }

    final List<Element> categories = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CATEGORY);
    if (!categories.isEmpty()) {
        entry.setType(categories.get(0).getAttribute(ODataConstants.ATOM_ATTR_TERM));
    }

    final List<Element> links = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_LINK);
    for (Element linkElem : links) {
        final AtomLink link = new AtomLink();
        link.setRel(linkElem.getAttribute(ODataConstants.ATTR_REL));
        link.setTitle(linkElem.getAttribute(ODataConstants.ATTR_TITLE));
        link.setHref(linkElem.getAttribute(ODataConstants.ATTR_HREF));

        if (ODataConstants.SELF_LINK_REL.equals(link.getRel())) {
            entry.setSelfLink(link);
        } else if (ODataConstants.EDIT_LINK_REL.equals(link.getRel())) {
            entry.setEditLink(link);
        } else if (link.getRel().startsWith(ODataConstants.NAVIGATION_LINK_REL)) {
            link.setType(linkElem.getAttribute(ODataConstants.ATTR_TYPE));
            entry.addNavigationLink(link);

            final List<Element> inlines = XMLUtils.getChildElements(linkElem, ODataConstants.ATOM_ELEM_INLINE);
            if (!inlines.isEmpty()) {
                final List<Element> entries = XMLUtils.getChildElements(inlines.get(0),
                        ODataConstants.ATOM_ELEM_ENTRY);
                if (!entries.isEmpty()) {
                    link.setInlineEntry(entry(entries.get(0)));
                }

                final List<Element> feeds = XMLUtils.getChildElements(inlines.get(0),
                        ODataConstants.ATOM_ELEM_FEED);
                if (!feeds.isEmpty()) {
                    link.setInlineFeed(feed(feeds.get(0)));
                }
            }
        } else if (link.getRel().startsWith(ODataConstants.ASSOCIATION_LINK_REL)) {
            entry.addAssociationLink(link);
        } else if (link.getRel().startsWith(ODataConstants.MEDIA_EDIT_LINK_REL)) {
            entry.addMediaEditLink(link);
        }
    }

    final List<Element> authors = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_AUTHOR);
    if (!authors.isEmpty()) {
        final AtomEntry.Author author = new AtomEntry.Author();
        for (Node child : XMLUtils.getChildNodes(input, Node.ELEMENT_NODE)) {
            if (ODataConstants.ATOM_ELEM_AUTHOR_NAME.equals(XMLUtils.getSimpleName(child))) {
                author.setName(child.getTextContent());
            } else if (ODataConstants.ATOM_ELEM_AUTHOR_URI.equals(XMLUtils.getSimpleName(child))) {
                author.setUri(child.getTextContent());
            } else if (ODataConstants.ATOM_ELEM_AUTHOR_EMAIL.equals(XMLUtils.getSimpleName(child))) {
                author.setEmail(child.getTextContent());
            }
        }
        if (!author.isEmpty()) {
            entry.setAuthor(author);
        }
    }

    final List<Element> actions = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_ACTION);
    for (Element action : actions) {
        final ODataOperation operation = new ODataOperation();
        operation.setMetadataAnchor(action.getAttribute(ODataConstants.ATTR_METADATA));
        operation.setTitle(action.getAttribute(ODataConstants.ATTR_TITLE));
        operation.setTarget(URI.create(action.getAttribute(ODataConstants.ATTR_TARGET)));

        entry.addOperation(operation);
    }

    final List<Element> contents = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CONTENT);
    if (!contents.isEmpty()) {
        final Element content = contents.get(0);

        List<Element> props = XMLUtils.getChildElements(content, ODataConstants.ELEM_PROPERTIES);
        if (props.isEmpty()) {
            entry.setMediaContentSource(content.getAttribute(ODataConstants.ATOM_ATTR_SRC));
            entry.setMediaContentType(content.getAttribute(ODataConstants.ATTR_TYPE));

            props = XMLUtils.getChildElements(input, ODataConstants.ELEM_PROPERTIES);
            if (!props.isEmpty()) {
                entry.setMediaEntryProperties(props.get(0));
            }
        } else {
            entry.setContent(props.get(0));
        }
    }

    return entry;
}

From source file:com.sun.socialsite.pojos.App.java

public static App readFromStream(InputStream in, URL urlToStore) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(in);
    in.close();/*from w  w w .j av a  2 s  .  c o  m*/

    App app = new App();
    app.setURL(urlToStore);

    Element modulePrefsElement = (Element) (doc.getElementsByTagName("ModulePrefs").item(0));
    app.setAuthor(modulePrefsElement.getAttribute("author"));
    app.setAuthorEmail(modulePrefsElement.getAttribute("author_email"));
    if (!"".equals(modulePrefsElement.getAttribute("author_link"))) {
        app.setAuthorLink(new URL(urlToStore, modulePrefsElement.getAttribute("author_link")));
    }
    app.setDescription(modulePrefsElement.getAttribute("description"));
    app.setDirectoryTitle(modulePrefsElement.getAttribute("directory_title"));
    if (!"".equals(modulePrefsElement.getAttribute("height"))) {
        app.setHeight(Integer.parseInt(modulePrefsElement.getAttribute("height")));
    }
    if (!"".equals(modulePrefsElement.getAttribute("show_in_directory"))) {
        app.setShowInDirectory(Boolean.valueOf(modulePrefsElement.getAttribute("show_in_directory")));
    }
    if (!"".equals(modulePrefsElement.getAttribute("scrolling"))) {
        app.setScrolling(Boolean.valueOf(modulePrefsElement.getAttribute("scrolling")));
    }
    if (!"".equals(modulePrefsElement.getAttribute("singleton"))) {
        app.setSingleton(Boolean.valueOf(modulePrefsElement.getAttribute("singleton")));
    }
    if (!"".equals(modulePrefsElement.getAttribute("thumbnail"))) {
        app.setThumbnail(new URL(urlToStore, modulePrefsElement.getAttribute("thumbnail")));
    }
    app.setTitle(modulePrefsElement.getAttribute("title"));
    if (!"".equals(modulePrefsElement.getAttribute("title_url"))) {
        app.setTitleURL(new URL(urlToStore, modulePrefsElement.getAttribute("title_url")));
    }
    if (!"".equals(modulePrefsElement.getAttribute("width"))) {
        app.setWidth(Integer.parseInt(modulePrefsElement.getAttribute("width")));
    }

    return app;
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static String getAttributeValue(Element element, String attr, boolean isRequired) {
    final String value = element.getAttribute(attr);
    if (StringUtils.isBlank(value)) {
        if (isRequired) {
            throw new UnparseableResponseException(
                    "Response XML rowset lacks value for attribute '" + attr + "'");
        }/*  ww  w.  j a v  a  2s .c  om*/
        return null;
    }
    return value;
}