Java написать атрибут XML со значением

Это мой первый пост в стеке, так что если что-то не так, наберитесь терпения...

Хорошо, мой вопрос, как я могу написать атрибут XML со значением. Результат будет примерно таким:

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

Я попробовал это:

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

Но это не работает.. результат:

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

setAttribute отсутствует... Что я делаю не так?

Вот код:

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;
    }
}

А вот класс Producto:

public class Producto {
        public String attributeColor;
}

1 ответ

Я просто хотел добавить комментарий, но пишу его как ответ, так как у меня еще нет этой привилегии. Я искал, чтобы добавить атрибут к узлу xml, и я наткнулся на этот пост.

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

Я добавил ребенка после установки атрибута.

Другие вопросы по тегам