使用java sax生成xml属性时遇到问题

使用java sax生成xml属性时遇到问题,java,xml,sax,Java,Xml,Sax,我正在使用java中的SAXAPI将csv转换为xml。我可以生成一个没有如下属性的简单xml文件 <item> <item_id>1500</item_id> <item_quantity>4</item_quantity> </item> 1500 4. 但是我找不到将id和quantity设置为item元素的属性的方法,比如 <item id=1500 quantity=4/> SAXAPI

我正在使用java中的SAXAPI将csv转换为xml。我可以生成一个没有如下属性的简单xml文件

<item>
 <item_id>1500</item_id>
 <item_quantity>4</item_quantity>
</item>

1500
4.
但是我找不到将id和quantity设置为item元素的属性的方法,比如

<item id=1500 quantity=4/>


SAXAPI似乎提供的所有方法都是
startElement
character
endElement
方法。(我知道这些方法中有
属性
参数,但我似乎根本无法设置属性)。

有一些不错的示例代码,包括添加属性

import java.io.*;
// Xerces 1 or 2 additional classes.
import org.apache.xml.serialize.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
[...]
FileOutputStream fos = new FileOutputStream(filename);
// XERCES 1 or 2 additionnal classes.
OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
of.setIndent(1);
of.setIndenting(true);
of.setDoctype(null,"users.dtd");
XMLSerializer serializer = new XMLSerializer(fos,of);
// SAX2.0 ContentHandler.
ContentHandler hd = serializer.asContentHandler();
hd.startDocument();
// Processing instruction sample.
//hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"users.xsl\"");
// USER attributes.
AttributesImpl atts = new AttributesImpl();
// USERS tag.
hd.startElement("","","USERS",atts);
// USER tags.
String[] id = {"PWD122","MX787","A4Q45"};
String[] type = {"customer","manager","employee"};
String[] desc = {"Tim@Home","Jack&Moud","John D'oé"};
for (int i=0;i<id.length;i++)
{
  atts.clear();
  atts.addAttribute("","","ID","CDATA",id[i]);
  atts.addAttribute("","","TYPE","CDATA",type[i]);
  hd.startElement("","","USER",atts);
  hd.characters(desc[i].toCharArray(),0,desc[i].length());
  hd.endElement("","","USER");
}
hd.endElement("","","USERS");
hd.endDocument();
fos.close();
import java.io.*;
//Xerces 1或2个附加类。
导入org.apache.xml.serialize.*;
导入org.xml.sax.*;
导入org.xml.sax.helpers.*;
[...]
FileOutputStream fos=新的FileOutputStream(文件名);
//XERCES 1或2个附加类。
OutputFormat of=新的OutputFormat(“XML”,“ISO-8859-1”,真);
设置缩进(1);
设置缩进(真);
setDoctype(null,“users.dtd”);
XMLSerializer serializer=新的XMLSerializer(fos,of);
//SAX2.0 ContentHandler。
ContentHandler hd=serializer.asContentHandler();
hd.startDocument();
//处理指令样本。
//处理指令(“xml样式表”,“类型=\”text/xsl\“href=\”users.xsl\”);
//用户属性。
AttributesImpl atts=新的AttributesImpl();
//用户标签。
hd.startElement(“用户”、“收件人”);
//用户标签。
字符串[]id={“PWD122”、“MX787”、“A4Q45”};
字符串[]类型={“客户”、“经理”、“员工”};
字符串[]desc={”Tim@Home“,”杰克和穆德“,”约翰·多埃“};

for(int i=0;it)有一个属性参数。您似乎无法使用它来设置属性。我的结论是:您使用该参数是错误的。请发布一个您试图如何设置属性的示例,我们可能可以修复它。