使用 java sax 生成 xml 属性时遇到问题 [英] having trouble generating xml attribute with java sax

查看:41
本文介绍了使用 java sax 生成 xml 属性时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 java 中使用 SAX api 将 csv 转换为 xml.我可以生成一个没有属性的简单xml文件,如

I am using SAX api in java to convert csv to xml. I can generate a simple xml file without attribute like

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

但我找不到将 id 和数量设置为 item 元素的属性的方法,例如

but I can't find the way to set id and quantity as attribute to item element, like

<item id=1500 quantity=4/>

所有 SAX api 似乎提供的是 startElementcharacterendElement 方法.(我知道这些方法中有 attribute 参数,但我似乎根本无法设置属性).

All SAX api seems to offer is startElement, character and endElement methods. (I know there is the attribute parameter in those method but I can't ever seem to set attribute at all).

推荐答案

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

There's some decent sample code here that includes adding attributes.

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();

这篇关于使用 java sax 生成 xml 属性时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆