Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static void setQNameAttribute(Element element, Attr attr, QName attributeQnameValue,
        Element definitionElement) {
    String attributeStringValue;/*  ww  w.  ja  v a  2  s.c o m*/

    if (attributeQnameValue == null) {
        attributeStringValue = "";
    } else if (XMLConstants.NULL_NS_URI.equals(attributeQnameValue.getNamespaceURI())) {
        if (QNameUtil.isPrefixUndeclared(attributeQnameValue.getPrefix())) {
            attributeStringValue = attributeQnameValue.getPrefix() + ":" + attributeQnameValue.getLocalPart(); // to give user a chance to see and fix this
        } else {
            attributeStringValue = attributeQnameValue.getLocalPart();
        }
    } else {
        String valuePrefix = lookupOrCreateNamespaceDeclaration(element, attributeQnameValue.getNamespaceURI(),
                attributeQnameValue.getPrefix(), definitionElement, false);
        assert StringUtils.isNotBlank(valuePrefix);
        attributeStringValue = valuePrefix + ":" + attributeQnameValue.getLocalPart();
    }

    NamedNodeMap attributes = element.getAttributes();
    checkValidXmlChars(attributeStringValue);
    attr.setValue(attributeStringValue);
    attributes.setNamedItem(attr);
}

From source file:eu.elf.license.LicenseParser.java

/**
 * Creates list of license model parameters
 *
 * @param declarationListElement - XML element <x:declarationList>
 * @return List of LicenseParam objects/*w  ww  . ja  va 2s  .  co m*/
 */
private static List<LicenseParam> createLicenseModelParamList(Element declarationListElement) {
    List<LicenseParam> paramList = new ArrayList<LicenseParam>();

    // Predefined Parameters - create as LicenseParamDisplay objects
    Element predefinedParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "predefinedParameters").item(0);

    if (predefinedParametersElement != null) {
        NodeList predefinedParametersParameterElementList = predefinedParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < predefinedParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) predefinedParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement,
                    "predefinedParameter");
            paramList.add(displayParam);

        }
    }

    // Configuration Parameters - might be LicenseParamDisplay || LicenseParamBln || LicenseParamEnum || LicenseParamInt || LicenseParamText
    Element configurationParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "configurationParameters").item(0);

    if (configurationParametersElement != null) {
        NodeList configurationParametersParameterElementList = configurationParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < configurationParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) configurationParametersParameterElementList.item(n);

            LicenseParam lp = null;
            Boolean isStringType = false;
            Boolean multiAttributeExists = false; // true for enumration type parameters
            //Boolean multiAttributeValue = false; // value of the multi attribute 
            //Boolean optionalAttribute = false;  // What does optional attribute signify???

            NamedNodeMap parameterElementAttributeMap = parameterElement.getAttributes();

            // Create appropriate subclass object based on the "type" and "multi" attributes
            for (int o = 0; o < parameterElementAttributeMap.getLength(); o++) {
                Attr attrs = (Attr) parameterElementAttributeMap.item(o);

                if (attrs.getNodeName().equals("type")) {
                    if (attrs.getNodeValue().equals("real")) {
                        lp = createLicenseParamInt(parameterElement, "configurationParameter");
                        paramList.add(lp);
                        //System.out.println("lp - name "+lpInt.getName());
                    } else if (attrs.getNodeValue().equals("string")) {
                        isStringType = true;
                    } else if (attrs.getNodeValue().equals("boolean")) {
                        lp = createLicenseParamBln(parameterElement, "configurationParameter");
                        paramList.add(lp);
                    }

                }
                if (attrs.getNodeName().equals("multi")) {
                    multiAttributeExists = true;
                    //if (attrs.getNodeValue().equals("true")) {

                    //multiAttributeValue = true;
                    //}
                    //else {
                    //multiAttributeExists = false;
                    //multiAttributeValue = false;
                    //}
                }
                // if (attrs.getNodeName().equals("optional")) {
                //    if (attrs.getNodeName().equals("true")) {
                //       optionalAttribute = true;
                //    }
                //    else {
                //       optionalAttribute = false;
                //    }
                // }

            }

            if (isStringType == true) {
                if (multiAttributeExists == true) {
                    lp = createLicenseParamEnum(parameterElement, "configurationParameter");
                    paramList.add(lp);

                    //if (optionalAttribute == true) {
                    //   
                    //    lp = createLicenseParamEnum(parameterElement, "configurationParameter");
                    //     paramList.add(lp);
                    //} 
                } else {
                    lp = createLicenseParamText(parameterElement, "configurationParameter");
                    paramList.add(lp);
                }
            }

        }
    }

    // Precalculated Parameters - create as LicenseParamDisplay objects
    Element precalculatedParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "precalculatedParameters").item(0);

    if (precalculatedParametersElement != null) {
        NodeList precalculatedParametersParameterElementList = precalculatedParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < precalculatedParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) precalculatedParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement,
                    "precalculatedParameter");
            paramList.add(displayParam);

        }
    }

    // Result Parameters - create as LicenseParamDisplay objects
    Element resultParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "resultParameters").item(0);

    if (resultParametersElement != null) {
        NodeList resultParametersParameterElementList = resultParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < resultParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) resultParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement, "resultParameter");
            paramList.add(displayParam);

        }
    }

    return paramList;
}

From source file:com.moviejukebox.reader.MovieJukeboxXMLReader.java

/**
 * Parse the person XML file from the jukebox
 *
 * @param xmlFile//w  ww  .  j  a  v a2  s.com
 * @param person
 * @return
 */
public boolean parsePersonXML(File xmlFile, Person person) {
    Document xmlDoc;
    try {
        xmlDoc = DOMHelper.getDocFromFile(xmlFile);
    } catch (MalformedURLException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (IOException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (ParserConfigurationException | SAXException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    }

    Node nPeople, nTemp;
    NodeList nlPeople = xmlDoc.getElementsByTagName("person");
    String sTemp;
    Element eTemp;
    NodeList nlTemp;
    for (int looper = 0; looper < nlPeople.getLength(); looper++) {
        nPeople = nlPeople.item(looper);
        if (nPeople.getNodeType() == Node.ELEMENT_NODE) {
            Element ePerson = (Element) nPeople;

            // Get IDs
            nlTemp = ePerson.getElementsByTagName("id");
            for (int idLoop = 0; idLoop < nlTemp.getLength(); idLoop++) {
                nTemp = nlTemp.item(idLoop);

                if (nTemp.getNodeType() == Node.ELEMENT_NODE) {
                    Element eId = (Element) nTemp;
                    String personDatabase = eId.getAttribute("persondb");
                    if (StringTools.isNotValidString(personDatabase)) {
                        personDatabase = ImdbPlugin.IMDB_PLUGIN_ID;
                    }
                    person.setId(personDatabase, eId.getTextContent());
                }
            }

            // Get Name
            eTemp = DOMHelper.getElementByName(ePerson, "name");
            if (eTemp != null) {
                sTemp = eTemp.getTextContent();
                if (StringTools.isNotValidString(person.getName())) {
                    person.setName(sTemp);
                } else {
                    person.addAka(sTemp);
                }
            }

            person.setTitle(DOMHelper.getValueFromElement(ePerson, "title"));
            person.setFilename(DOMHelper.getValueFromElement(ePerson, "baseFilename"));
            person.setBiography(DOMHelper.getValueFromElement(ePerson, "biography"));
            person.setYear(DOMHelper.getValueFromElement(ePerson, "birthday"));
            person.setBirthPlace(DOMHelper.getValueFromElement(ePerson, "birthplace"));
            person.setBirthName(DOMHelper.getValueFromElement(ePerson, "birthname"));
            person.setUrl(DOMHelper.getValueFromElement(ePerson, "url"));
            person.setPhotoFilename(DOMHelper.getValueFromElement(ePerson, "photoFile"));
            person.setPhotoURL(DOMHelper.getValueFromElement(ePerson, "photoURL"));
            person.setBackdropFilename(DOMHelper.getValueFromElement(ePerson, "backdropFile"));
            person.setBackdropURL(DOMHelper.getValueFromElement(ePerson, "backdropURL"));
            person.setKnownMovies(Integer.parseInt(DOMHelper.getValueFromElement(ePerson, "knownMovies")));
            person.setVersion(Integer.parseInt(DOMHelper.getValueFromElement(ePerson, "version")));
            person.setLastModifiedAt(DOMHelper.getValueFromElement(ePerson, "lastModifiedAt"));

            nlTemp = ePerson.getElementsByTagName("movie");
            for (int movieLoop = 0; movieLoop < nlTemp.getLength(); movieLoop++) {
                nTemp = nlTemp.item(movieLoop);
                if (nTemp.getNodeType() == Node.ELEMENT_NODE) {
                    Filmography film = new Filmography();
                    Element eMovie = (Element) nTemp;

                    film.setId(eMovie.getAttribute("id"));

                    // Process the attributes
                    NamedNodeMap nnmAttr = eMovie.getAttributes();
                    for (int i = 0; i < nnmAttr.getLength(); i++) {
                        Node nAttr = nnmAttr.item(i);
                        String ns = nAttr.getNodeName();

                        if ("id".equalsIgnoreCase(ns)) {
                            film.setId(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.toLowerCase().contains(ID)) {
                            person.setId(ns.substring(3), nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(NAME)) {
                            film.setName(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(TITLE)) {
                            film.setTitle(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(ORIGINAL_TITLE)) {
                            film.setOriginalTitle(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(YEAR)) {
                            film.setYear(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(RATING)) {
                            film.setRating(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(CHARACTER)) {
                            film.setCharacter(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(JOB)) {
                            film.setJob(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(DEPARTMENT)) {
                            film.setDepartment(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(URL)) {
                            film.setUrl(nAttr.getTextContent());
                            //continue; // Last contine not needed
                        }
                    }

                    // Set the filename
                    film.setFilename(eMovie.getTextContent());
                    film.setDirty(Boolean.FALSE);
                    person.addFilm(film);
                }
            }

            person.setFilename();
            person.setDirty(Boolean.FALSE);

            // Only process the first in the file
            return Boolean.TRUE;
        }
    }

    // FAILED
    return Boolean.FALSE;
}

From source file:jp.co.acroquest.jsonic.Formatter.java

public boolean format(final JSON json, final Context context, final Object src, final Object o,
        final OutputSource out) throws Exception {
    Element elem = (Element) o;
    out.append('[');
    StringFormatter.serialize(context, elem.getTagName(), out);

    out.append(',');
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth() + 1; j++)
            out.append('\t');
    }/*from   w w  w  . ja va 2  s  .c  o  m*/
    out.append('{');
    if (elem.hasAttributes()) {
        NamedNodeMap names = elem.getAttributes();
        for (int i = 0; i < names.getLength(); i++) {
            if (i != 0) {
                out.append(',');
            }
            if (context.isPrettyPrint() && names.getLength() > 1) {
                out.append('\n');
                for (int j = 0; j < context.getDepth() + 2; j++)
                    out.append('\t');
            }
            Node node = names.item(i);
            if (node instanceof Attr) {
                StringFormatter.serialize(context, node.getNodeName(), out);
                out.append(':');
                if (context.isPrettyPrint())
                    out.append(' ');
                StringFormatter.serialize(context, node.getNodeValue(), out);
            }
        }
        if (context.isPrettyPrint() && names.getLength() > 1) {
            out.append('\n');
            for (int j = 0; j < context.getDepth() + 1; j++)
                out.append('\t');
        }
    }
    out.append('}');
    if (elem.hasChildNodes()) {
        NodeList nodes = elem.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Object value = nodes.item(i);
            if ((value instanceof Element) || (value instanceof CharacterData && !(value instanceof Comment))) {
                out.append(',');
                if (context.isPrettyPrint()) {
                    out.append('\n');
                    for (int j = 0; j < context.getDepth() + 1; j++)
                        out.append('\t');
                }
                context.enter(i + 2);
                value = json.preformatInternal(context, value);
                json.formatInternal(context, value, out);
                context.exit();
                if (out instanceof Flushable)
                    ((Flushable) out).flush();
            }
        }
    }
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth(); j++)
            out.append('\t');
    }
    out.append(']');
    return true;
}

From source file:jef.tools.XMLUtils.java

/**
 * //from w ww.j ava 2 s . c om
 * 
 * @param element
 *            ?
 */
public static void clearAttribute(Element element) {
    for (Node node : toArray(element.getAttributes())) {
        element.removeAttributeNode((Attr) node);
    }
}

From source file:iristk.flow.FlowCompiler.java

private Map<String, String> getParameters(Element elem) throws FlowCompilerException {
    NamedNodeMap attributes = elem.getAttributes();
    NodeList childNodes = elem.getChildNodes();
    Map<QName, String> otherAttributes = new HashMap<>();
    for (int i = 0; i < attributes.getLength(); i++) {
        if (attributes.item(i).getNamespaceURI() == null
                || !attributes.item(i).getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")) {
            otherAttributes.put(new QName("iristk.flow.param", attributes.item(i).getLocalName()),
                    attributes.item(i).getNodeValue());
        }//from w  ww .  ja  va2  s. c  o m
    }
    ArrayList<Object> content = new ArrayList<>();
    for (int i = 0; i < childNodes.getLength(); i++) {
        content.add(childNodes.item(i));
    }
    return getParameters(otherAttributes, content, elem);
}

From source file:net.hasor.rsf.spring.parser.RsfDefinitionParser.java

/** ?Xml  */
@Override/*from w  ww  .ja  v  a  2  s.  c o m*/
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // Spring 
    String version = SpringVersion.getVersion();
    version = StringUtils.isBlank(version) ? "?" : version;
    Map customEditors = null;
    if (version.charAt(0) == '4' || version.charAt(0) == '5') {
        customEditors = new HashMap<Class<?>, Class<? extends java.beans.PropertyEditor>>();
        customEditors.put(InterAddress.class, RsfAddressPropertyEditor.class);
    } else {
        customEditors = new HashMap();
        customEditors.put("net.hasor.rsf.InterAddress", new RsfAddressPropertyEditor());
    }
    //
    // . Bean 
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
    builder.getRawBeanDefinition().setBeanClass(CustomEditorConfigurer.class);
    builder.setScope(BeanDefinition.SCOPE_SINGLETON);//?
    builder.addPropertyValue("customEditors", customEditors);
    //
    //  .,BeanID net.hasor.rsf.spring.RsfAddressPropertyEditor
    AbstractBeanDefinition propEditors = builder.getBeanDefinition();
    String beanID = RsfAddressPropertyEditor.class.getName();
    BeanDefinitionHolder holder = new BeanDefinitionHolder(propEditors, beanID);
    BeanDefinitionReaderUtils.registerBeanDefinition(holder, parserContext.getRegistry());
    parserContext.registerComponent(new BeanComponentDefinition(holder));
    //
    //
    NamedNodeMap attributes = element.getAttributes();
    //
    return null;
}

From source file:iristk.flow.FlowCompiler.java

private String createExpression(Element en) throws FlowCompilerException {
    String estring = "";
    estring += "<" + en.getLocalName();
    for (int j = 0; j < en.getAttributes().getLength(); j++) {
        Attr attr = (Attr) en.getAttributes().item(j);
        if (!(attr.getNamespaceURI() != null && attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/"))
                && !attr.getLocalName().equals("xmlns") && !attr.getLocalName().equals("xsi")) {
            estring += " " + attr.getLocalName() + "=\\\"" + attr.getValue() + "\\\"";
        }/*from   ww  w.  j  a  v  a2 s. c o m*/
    }
    if (en.getChildNodes().getLength() == 0) {
        estring += "/>";
        return "\"" + estring + "\"";
    } else {
        String varName = varname("string");
        code.println("StringCreator " + varName + " = new StringCreator();");
        List<Object> children = new ArrayList<>();
        estring += ">";
        children.add(estring);
        for (int i = 0; i < en.getChildNodes().getLength(); i++) {
            children.add(en.getChildNodes().item(i));
        }
        children.add("</" + en.getLocalName() + ">");
        printActions(children, en, varName);
        return varName + ".toString()";
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ?/*from   www .  j  a va  2 s .c om*/
 * 
 * @param e
 *            
 * @param subElementAsAttr
 *            trueElement?<br>
 *            
 * 
 *            <pre>
 * &lt;Foo size="103" name="Karen"&gt;
 *   &lt;dob&gt;2012-4-12&lt;/dobh&gt;
 *   &lt;dod&gt;2052-4-12&lt;/dodh&gt;
 * &lt;/Foo&gt;
 * </pre>
 * 
 *            subElementAsAttr=falsedob,dod?true?
 * @return
 */
public static Map<String, String> getAttributesMap(Element e, boolean subElementAsAttr) {
    Map<String, String> attribs = new HashMap<String, String>();
    if (e == null)
        return attribs;
    NamedNodeMap nmp = e.getAttributes();
    for (int i = 0; i < nmp.getLength(); i++) {
        Attr child = (Attr) nmp.item(i);
        attribs.put(StringEscapeUtils.unescapeHtml(child.getName()),
                StringEscapeUtils.unescapeHtml(child.getValue()));
    }
    if (subElementAsAttr) {
        NodeList nds = e.getChildNodes();
        for (int i = 0; i < nds.getLength(); i++) {
            Node node = nds.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element sub = (Element) node;
            String key = sub.getNodeName();
            String value = nodeText(sub);
            if (attribs.containsKey(key)) {
                attribs.put(key, attribs.get(key) + "," + value);
            } else {
                attribs.put(key, value);
            }
        }
    }
    return attribs;
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to bind Channel element/*  w w w.  j  ava 2 s.co  m*/
 * 
 * @param channelElement Channel element
 * @return Channel data object
 * @throws InkMLException
 */
protected Channel getChannel(final Element channelElement) throws InkMLException {
    Channel channel = null;
    final String chnName = channelElement.getAttribute("name");
    if ("".equals(chnName)) {
        throw new InkMLException("Channel element must have value for 'name' attribute");
    } else {
        channel = new Channel(chnName);
    }
    // checking for intermittend channel
    if ("intermittentChannels".equalsIgnoreCase(channelElement.getParentNode().getLocalName())) {
        channel.setIntermittent(true);
    }

    // Extract and set Attribute values
    final NamedNodeMap attrMap = channelElement.getAttributes();
    final int length = attrMap.getLength();
    for (int i = 0; i < length; i++) {
        final Node attr = attrMap.item(i);
        channel.setAttribute(attr.getLocalName(), attr.getNodeValue());
    }
    return channel;
}