MikeEng
MikeEng

Reputation: 11

java write xml attribute with value

This is my first post on Stack, so if there is something wrong, be patient ...

Ok, my question is how can I write an XML attribute with value. The result would be something like this:

<GroupAttribute>
<Attribute name = "Color"> Pink </Attribute>
.....
</GroupAttribute>

I tried this:

Element attribute = doc.createElement ("attribute");
groupAttribute.appendChild (attribute);
attribute.setAttribute ("attributeType" p.attributeColor);
groupAttribute.appendChild (getCompanyElements (doc, attribute, "attribute", p.attributeColor));

But it does not work.. the result is:

<GroupAttribute>
    <Attribute> Pink </Attribute>    
    .....
    </GroupAttribute>

the setAttribute is missing ... What am I doing wrong?

Here the code:

import com.opencsv.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 *
 * @author Mike
 */
public class prueba {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        List<Producto> prods = new ArrayList<Producto>();

        try {
            CSVReader reader;
            reader = new CSVReader(new FileReader("C:\\Temp\\feeds\\Product_Prueba.csv"), ';');

            String[] nextLine;
            try {
                while ((nextLine = reader.readNext()) != null) {
                    // nextLine[] is an array of values from the line
                    //System.out.println(Arrays.toString(nextLine));

                    //Lee
                    Producto p;
                    p = new Producto();
                    p.attributeColor = "Pink";

                    prods.add(p);
                }
            } catch (IOException ex) {
                Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
        }
        xeraXML(prods);
    }

    static void xeraXML(List<Producto> ps) {
        DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder;
        try {
            icBuilder = icFactory.newDocumentBuilder();
            Document doc = icBuilder.newDocument();
            Element mainRootElement = doc.createElement("productRequest");
            doc.appendChild(mainRootElement);
            for (Iterator<Producto> i = ps.iterator(); i.hasNext();) {
                Producto p;
                p = i.next();
                mainRootElement.appendChild(getProductElement(doc, p));
            }

            // output DOM XML to console 
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult console = new StreamResult(System.out);
            //StreamResult out = new StreamResult("C:\\Temp\\results\\resultado.xml");
            transformer.transform(source, console);
            //transformer.transform(source, out);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Element getProductElement(Document doc /*String localizedFor,*/, Producto p) {
        Element groupAttribute = doc.createElement("groupAttribute");
        Element attribute = doc.createElement("attribute");
        groupAttribute.appendChild(attribute);
        attribute.setAttribute("attributeType", p.attributeColor);
        groupAttribute.appendChild(getElements(doc, attribute, "attribute", p.attributeColor));
        return groupAttribute;
    }

    private static Node getElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}

And here the Producto class:

public class Producto {
        public String attributeColor;
}

Upvotes: 1

Views: 2832

Answers (1)

KKK
KKK

Reputation: 121

I just wanted to add the comment but am writing it as an answer since I don't have that privilege yet. I was looking to add the attribute to the xml node and I came across this post.

        dependency = dom.createElement("dependency");
        dependency.setAttribute("type", "value");
        dependencies.appendChild(dependency);

I added the child after setting the attribute.

Upvotes: 1

Related Questions