SAX生成XML时空指针

在同时SAX方式生成XML时处理空指针问题

SAX生成XML时空指针_第1张图片

代码:
// ......
handler.setResult(resultxml);
handler.startDocument();

// xml元素
AttributesImpl attr = new AttributesImpl();
attr.addAttribute("", "", "xmlns:xsi", "", "http://www.w3.org/2001/XMLSchema-instance");
attr.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "", "关联关系XML Schema-3.0.xsd");
attr.addAttribute("", "", "License", "", "Gicom");
handler.startElement("", "", "Document", attr);

attr = new AttributesImpl();
attr.addAttribute("", "", "version", "", null); // (1处) 元素Events的属性为null,导致的NullPointerException
handler.startElement("", "", "Events", attr); // (1’处) 

attr = new AttributesImpl();
attr.addAttribute("", "", "name", "", "RelationCreate");
handler.startElement("", "", "Event", attr); // (2处)  java.lang.NullPointerException

空指针指向
handler.startElement("", "", "Event", attr);
而当前行,handler和attr均非空


错误信息:
java.lang.NullPointerException
	at org.apache.xml.serializer.ToStream.writeAttrString(ToStream.java:1915)
	at org.apache.xml.serializer.ToStream.processAttributes(ToStream.java:1895)
	at org.apache.xml.serializer.ToStream.closeStartTag(ToStream.java:2360)
	at org.apache.xml.serializer.ToStream.startElement(ToStream.java:1732)
	at org.apache.xalan.transformer.TransformerIdentityImpl.startElement(TransformerIdentityImpl.java:1020)
	at com.geap.gpwms.preStorage.service.impl.PreStorageServiceImpl.startElement(PreStorageServiceImpl.java:2784)
	at com.geap.gpwms.preStorage.service.impl.PreStorageServiceImpl.createRelationFile4storage(PreStorageServiceImpl.java:2626)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)


其实原因在于handler处理的上一个元素(1’处)不会立即解析当前属性,当调用handler做下一步操作时,才解析。导致的空指针指向与实际情况不一致。

另外,关于上面一点说明我们从单个闭合标签的出现也可以说明。
handler.startElement("", "", "Code", code); // (3)
handler.endElement("", "", "Code"); //(4)

得到的文件是:
<Code curCode="81004670013244603097"/>
而不是:
<Code curCode="81004670013244603097"></Code>
说明handler是在解析到(4)是才写入文件,并且发现Code开启后马上关闭,所以是一个闭合标签。


你可能感兴趣的:(java,xml,sax)