java用值写xml属性

时间:2016-07-12 07:46:47

标签: java xml dom setattribute

这是我在Stack上的第一篇文章,所以如果出现问题,请耐心等待......

好的,我的问题是如何编写带有值的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 个答案:

答案 0 :(得分:1)

我只是想添加评论,但我正在写这个答案,因为我还没有这个特权。我想要将属性添加到xml节点,我发现了这篇文章。

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

我在设置属性后添加了孩子。