【问题标题】:having trouble generating xml attribute with java sax使用 java sax 生成 xml 属性时遇到问题
【发布时间】:2009-12-21 02:34:35
【问题描述】:

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

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

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

<item id=1500 quantity=4/>

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

【问题讨论】:

  • 有一个属性参数。您似乎无法使用它来设置属性。我的结论:您使用该参数错误。发布您如何尝试设置属性的示例,我们也许可以修复它。

标签: java xml sax


【解决方案1】:

有一些不错的示例代码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 = {"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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多