2009-12-21 7 views
0

java에서 SAX API를 사용하여 CSV를 XML로 변환하고 있습니다. 나는자바 색소폰으로 XML 속성을 생성하는 데 문제가 있습니다.

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

같은 속성이없는 간단한 XML 파일을 생성 할 수 있지만, 모든 SAX API를 제공하는 것 나는

<item id=1500 quantity=4/> 

같은 항목 요소에 속성으로 ID와 수량을 설정할 수있는 방법을 찾을 수 없습니다 startElement, characterendElement 방법입니다. (나는 그 방법에 attribute 매개 변수가 있다는 것을 알고 있지만, 나는 전혀 속성을 설정하지 않는 것처럼 보입니다.)

+4

속성 매개 변수가 있습니다. 속성을 설정하는 데 사용할 수는 없습니다. 내 결론 : 당신은 그 매개 변수를 잘못 사용하고 있습니다. 속성을 설정하는 방법에 대한 샘플을 게시하면 수정할 수 있습니다. –

답변

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(); 
관련 문제