Example usage for org.jdom2 Element getAttributes

List of usage examples for org.jdom2 Element getAttributes

Introduction

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

Prototype

public List<Attribute> getAttributes() 

Source Link

Document

This returns the complete set of attributes for this element, as a List of Attribute objects in no particular order, or an empty list if there are none.

Usage

From source file:br.com.gsoftwares.util.ImportClient.java

private void lerarq(String caminho) throws Exception {
    //Aqui voc informa o nome do arquivo XML.  
    File f = new File(caminho);
    File[] arquivos = f.listFiles();
    //Criamos uma classe SAXBuilder que vai processar o XML  
    for (File fileTmp : arquivos) {

        SAXBuilder sb = new SAXBuilder();

        //Este documento agora possui toda a estrutura do arquivo.  
        Document d;/*w ww .  j  a v  a  2 s .com*/
        try {
            d = sb.build(fileTmp);
            //Recuperamos o elemento root  
            Element nfe = d.getRootElement();

            //Recuperamos os atributos filhos (Attributes)  
            List atributes = nfe.getAttributes();
            Iterator i_atr = atributes.iterator();

            //Iteramos com os atributos filhos  
            while (i_atr.hasNext()) {
                Attribute atrib = (Attribute) i_atr.next();
                //System.out.println("\nattribute de (" + nfe.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
            }
            //Recuperamos os elementos filhos (children)  
            List elements = nfe.getChildren();
            Iterator i = elements.iterator();

            //Iteramos com os elementos filhos, e filhos do dos filhos  
            while (i.hasNext()) {
                Element element = (Element) i.next();
                //System.out.println("element:" + element.getName());
                trataElement(element);
            }
            Salvar();
        } catch (JDOMException | IOException ex) {
            Logger.getLogger(LerArqXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "", JOptionPane.INFORMATION_MESSAGE);
}

From source file:br.com.gsoftwares.util.ImportClient.java

private void trataElement(Element element) throws Exception {

    //Recuperamos os atributos filhos (Attributes)  
    List atributes = element.getAttributes();
    Iterator i_atr = atributes.iterator();

    //Iteramos com os atributos filhos  
    while (i_atr.hasNext()) {
        Attribute atrib = (Attribute) i_atr.next();
        //System.out.println("\nattribute de (" + element.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
    }//from   www. j a v a2 s  .  c  om
    //Recuperamos os elementos filhos (children)  
    List elements = element.getChildren();
    Iterator it = elements.iterator();

    //Iteramos com os elementos filhos, e filhos do dos filhos  
    while (it.hasNext()) {
        Element el = (Element) it.next();
        //System.out.println(el.getName() + " - " + el.getText());
        switch (el.getName()) {
        case "CPF":
            CPF = el.getText();
            Tipo = "F";
            break;
        case "CNPJ":
            CPF = el.getText();
            Tipo = "J";
            break;
        case "xNome":
            Nome = el.getText();
            Apelido = "";
            break;
        case "xLgr":
            Rua = el.getText();
            break;
        case "nro":
            numero = el.getText();
            break;
        case "xCpl":
            Comp = el.getText();
            break;
        case "xBairro":
            Bairro = el.getText();
            break;
        case "cMun":
            Cod_Mun = el.getText();
            break;
        case "xMun":
            Cidade = el.getText();
            break;
        case "UF":
            Estado = el.getText();
            break;
        case "CEP":
            Cep = el.getText();
            break;
        case "fone":
            Telefone = el.getText();
            break;
        case "IE":
            if (el.getText().equals("ISENTO")) {
                Tipo_ins = "2";
                Ins = "ISENTO";
            } else {
                if (el.getText().contains("^[0-9]*$")) {
                    Tipo_ins = "1";
                    Ins = el.getText();
                } else {
                    Tipo_ins = "9";
                    Ins = "";
                }
                break;
            }
        case "email":
            email = el.getText();
            break;
        }

        trataElement(el);
    }
}

From source file:br.com.gsoftwares.util.ImportProduto.java

private void lerarq(String caminho) throws Exception {
    //Aqui voc informa o nome do arquivo XML.  
    File f = new File(caminho);
    File[] arquivos = f.listFiles();
    //Criamos uma classe SAXBuilder que vai processar o XML  
    for (File fileTmp : arquivos) {

        SAXBuilder sb = new SAXBuilder();

        //Este documento agora possui toda a estrutura do arquivo.  
        Document d;// ww w. j  av a  2s  .  c om
        try {
            d = sb.build(fileTmp);
            //Recuperamos o elemento root  
            Element nfe = d.getRootElement();

            //Recuperamos os atributos filhos (Attributes)  
            List atributes = nfe.getAttributes();
            Iterator i_atr = atributes.iterator();

            //Iteramos com os atributos filhos  
            while (i_atr.hasNext()) {
                Attribute atrib = (Attribute) i_atr.next();
                //System.out.println("\nattribute de (" + nfe.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
            }
            //Recuperamos os elementos filhos (children)  
            List elements = nfe.getChildren();
            Iterator i = elements.iterator();

            //Iteramos com os elementos filhos, e filhos do dos filhos  
            while (i.hasNext()) {
                Element element = (Element) i.next();
                //System.out.println("element:" + element.getName());
                trataElement(element);
            }
            //Salvar();
        } catch (JDOMException | IOException ex) {
            Logger.getLogger(LerArqXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "", JOptionPane.INFORMATION_MESSAGE);
}

From source file:br.com.gsoftwares.util.ImportProduto.java

private void trataElement(Element element) throws Exception {

    //Recuperamos os atributos filhos (Attributes)  
    List atributes = element.getAttributes();
    Iterator i_atr = atributes.iterator();

    //Iteramos com os atributos filhos  
    while (i_atr.hasNext()) {
        Attribute atrib = (Attribute) i_atr.next();
        //System.out.println("\nattribute de (" + element.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
    }/*ww  w .j a v  a2s  .c  o  m*/
    //Recuperamos os elementos filhos (children)  
    List elements = element.getChildren();
    Iterator it = elements.iterator();

    //Iteramos com os elementos filhos, e filhos do dos filhos  
    while (it.hasNext()) {
        Element el = (Element) it.next();
        System.out.println(el.getName() + " - " + el.getText());
        switch (el.getName()) {
        case "cProd":
            CPF = el.getText();
            Tipo = "F";
            break;
        case "xProd":
            CPF = el.getText();
            Tipo = "J";
            break;
        case "NCM":
            Nome = el.getText();
            Apelido = "";
            break;
        case "uCom":
            Rua = el.getText();
            break;
        case "orig":
            numero = el.getText();
            break;
        }

        trataElement(el);
    }
}

From source file:ca.nrc.cadc.xml.JsonOutputter.java

License:Open Source License

private boolean writeAttributes(Element e, PrintWriter w, int i) throws IOException {
    boolean ret = writeSchemaAttributes(e, w, i);

    Iterator<Attribute> iter = e.getAttributes().iterator();
    if (ret && iter.hasNext())
        w.print(",");
    while (iter.hasNext()) {
        ret = true;/*from w ww . ja  v a  2 s .  c om*/
        Attribute a = iter.next();
        indent(w, i);
        w.print(QUOTE);
        w.print("@");
        if (StringUtil.hasText(a.getNamespacePrefix())) {
            w.print(a.getNamespacePrefix());
            w.print(":");
        }
        w.print(a.getName());
        w.print(QUOTE);
        w.print(" : ");
        if (isBoolean(e.getName(), a.getValue()) || isNumeric(e.getName(), a.getValue())) {
            w.print(a.getValue());
        } else {
            w.print(QUOTE);
            w.print(a.getValue());
            w.print(QUOTE);
        }
        if (iter.hasNext())
            w.print(",");
    }

    return ret;
}

From source file:com.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

/**
 * Creates a result specification for this node. Does not create the actual result object,
 * since there's no guarantee that that object will be immutable.
 *//*from  w  ww .ja  va2  s  . co m*/
private ResultNode parseResult(final Element element, final ResultSpec resultSpec)
        throws DecisionTreeParserException {
    final ResultNode.Builder builder = new ResultNode.Builder(resultSpec);
    for (final Attribute attribute : element.getAttributes()) {
        final String name = attribute.getName();
        final String value = attribute.getValue();
        builder.addAttribute(name, value);
    }

    return builder.build();
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void getElementString(final Element e, final StringBuilder str, final int depth,
        final int maxDepth, final boolean showDots) {
    addSpacing(str, depth);//from   w  w  w.  ja  v  a 2 s.co m
    str.append('<');
    str.append(e.getName());
    str.append(' ');
    final List<Attribute> attrs = e.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        final Attribute attr = attrs.get(i);
        str.append(attr.getName());
        str.append("=\"");
        str.append(attr.getValue());
        str.append('"');
        if (i < attrs.size() - 1) {
            str.append(' ');
        }
    }
    if (!e.getChildren().isEmpty() || !"".equals(e.getText())) {
        str.append('>');
        if (depth < maxDepth) {
            str.append('\n');
            for (final Element child : (List<Element>) e.getChildren()) {
                getElementString(child, str, depth + 1, maxDepth, showDots);
            }
            if (!"".equals(e.getText())) {
                addSpacing(str, depth + 1);
                str.append(e.getText());
                str.append('\n');
            }
        } else if (showDots) {
            str.append('\n');
            addSpacing(str, depth + 1);
            str.append("...");
            str.append('\n');
        }
        addSpacing(str, depth);
        str.append("</");
        str.append(e.getName());
        str.append('>');
    } else {
        str.append("/>");
    }
    str.append('\n');
}

From source file:com.c4om.utils.xmlutils.JDOMUtils.java

License:Apache License

/**
 * Method that checks whether two elements are the same in the following way:
 * <ul>/*from   w  w  w.j  a va2  s  . c o  m*/
 * <li>Have the same name</li>
 * <li>Have the same namespace URI</li>
 * <li>Have the same attribute sets (names, namespaces and values)</li>
 * </ul>
 * @param element1 one element
 * @param element2 another element
 * @return the result of the comparison
 */
public static boolean elementsEqualAtCNameAndAttributes(Element element1, Element element2) {
    boolean haveSameName = element1.getName().equals(element2.getName());
    boolean haveSameNamespaceURI = element1.getNamespaceURI().equals(element2.getNamespaceURI());
    Set<Attribute> attrSet1 = new HashSet<>(element1.getAttributes());
    Set<Attribute> attrSet2 = new HashSet<>(element2.getAttributes());
    boolean attrSetsEquals = attrSet1.equals(attrSet2);
    return haveSameName && haveSameNamespaceURI & attrSetsEquals;
}

From source file:com.c4om.utils.xmlutils.XPathUtils.java

License:Apache License

/**
 * It returns a path to a single element. The element (and its ancestors) is distinguished via its 
 * attributes set.//w w w .ja v  a 2s . c om
 * @param currentElement the element whose path is to be calculated
 * @param contextElement the element to which a relative path will be calculated (null for an absolute path).
 * @return the path.
 * @throws IllegalArgumentException if the currentElement is not descendant of the contextElement
 * 
 */
public static String generateAttributeBasedPath(Element currentElement, Element contextElement) {
    StringBuilder builder = new StringBuilder();
    Element parent = currentElement.getParentElement();
    if (contextElement != null) {
        IteratorIterable<Element> descendants = contextElement.getDescendants(Filters.element());
        Set<Element> descendantsSet = ImmutableSet.copyOf((Iterable<Element>) descendants);
        if (!descendantsSet.contains(currentElement)) {
            throw new IllegalArgumentException("The provided element is not descendant of the stopElement");
        }
    }
    if (parent != contextElement) {
        String pathToParent = generateAttributeBasedPath(parent, contextElement);
        builder.append(pathToParent);
    } else if (contextElement != null) {
        builder.insert(0, ".");
    }
    builder.append("/");
    builder.append(currentElement.getQualifiedName());
    String filter = "[" + generateAttributesFilter(currentElement.getAttributes()) + "]";
    builder.append(filter);
    String result = builder.toString();
    return result;
}

From source file:com.izforge.izpack.util.xmlmerge.action.FullMergeAction.java

License:Open Source License

/**
 * Adds attributes from in element to out element.
 *
 * @param out out element/*from  ww  w .  j a  va2s.co m*/
 * @param in in element
 */
private void addAttributes(Element out, Element in) {

    LinkedHashMap<String, Attribute> allAttributes = new LinkedHashMap<String, Attribute>();

    List<Attribute> outAttributes = new ArrayList<Attribute>(out.getAttributes());
    List<Attribute> inAttributes = new ArrayList<Attribute>(in.getAttributes());

    for (Attribute attr : outAttributes) {
        attr.detach();
        allAttributes.put(attr.getQualifiedName(), attr);
        logger.fine("adding attr from out:" + attr);
    }

    for (Attribute attr : inAttributes) {
        attr.detach();
        allAttributes.put(attr.getQualifiedName(), attr);
        logger.fine("adding attr from in:" + attr);
    }

    out.setAttributes(new ArrayList<Attribute>(allAttributes.values()));
}