怪事情,高手帮忙讲解一哈好?
我用以下代码把一个数据库文件生成XML文件
public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
ResultSet rs = null;
String colName;
try {
pst = con.prepareStatement( "SELECT * FROM master ");
rs = pst.executeQuery();
Document document = new Document(new Element( "根元素 ")); //创建文档,并设根元素
ResultSetMetaData rsmd = rs.getMetaData(); //获取字段名,返回ResultSetMetaData对像
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
Element element0 = new Element( "users "); //创建元素 生成JDOM树
document.getRootElement().addContent(element0);
// Element element2 = new Element( "userphone ");
// element0.addContent(element2);
for (int i = 1; i <= numberOfColumns; i++) {
try {
colName = new String(rs.getString(i));
//构造元素节点和文本节点
Element element = new Element(rsmd.getColumnName(i)).setText(colName);
element0.addContent(element);
} catch (Exception ex1) {
}
}
}
//org.jdom.output.XMLOutputter
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
try {
//生成XML文件路径
outp.output(document,new FileOutputStream( "aa.xml "));
} catch (IOException ex2) {
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
然后再用以下代码读取XML里面的元素
public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
try {
BufferedReader br = new BufferedReader(new FileReader(
"aaa.xml "));
DOMParser parser = new DOMParser();
parser.parse(new InputSource(br));
org.w3c.dom.Document doc = parser.getDocument();
org.w3c.dom.NodeList nl = doc.getElementsByTagName( "* ");
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
System.out.println(n.getNodeName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
他报一个异常
org.xml.sax.SAXParseException: Element type "鏍瑰厓绱 " must be followed by either attribute specifications, "> " or "/> ".
at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213)
at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XMLDocumentScanner.java:579)
at org.apache.xerces.framework.XMLDocumentScanner.abortMarkup(XMLDocumentScanner.java:628)
at org.apache.xerces.framework.XMLDocumentScanner.scanElement(XMLDocumentScanner.java:1800)
at org.apache.xerces.framework.XMLDocumentScanner$ContentDispatcher.dispatch(XMLDocumentScanner.java:949)
at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentScanner.java:381)
at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
at servlet.XMLInsetDB.main(XMLInsetDB.java:27)
读XML文件这个类是没有问题的
其他的XML文件也读得出来值
就是用类生成出来的XML文件就读不出来
生成出来的XML数据绝对是规范的
也看不出来有啥问题得
晕死
高手帮帮忙
讲解一哈
谢了
[解决办法]
好象是编码问题,存取都用unicode
[解决办法]
楼上说的没错,生成xml文件头的编码也一定要正确