2009-12-21 82 views
0

我在java中使用SAX api將csv轉換爲xml。我才能不用屬性的簡單的XML文件中像在使用java sax生成xml屬性時遇到問題

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

,但我無法找到設置ID和數量的屬性項元素的方法,像

<item id=1500 quantity=4/> 

所有SAX API似乎提供是startElement,characterendElement方法。 (我知道在這些方法中有attribute參數,但我根本無法設置屬性)。

+4

有一個屬性參數。您似乎無法使用它來設置屬性。我的結論是:你使用的是錯誤的參數。發表您如何設置屬性的示例,並且我們可能可以修復它。 – 2009-12-21 02:37:38

回答

0

有一些體面的示例代碼here,其中包括添加屬性。

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 = {"[email protected]","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();