Gen*_*Jam 5 java xml exception-handling exception
这真让我抓狂.我已经将这段代码用于许多不同的项目,但这是第一次给我这种类型的错误.这是整个XML文件:
<layers>
<layer name="Layer 1" h="400" w="272" z="0" y="98" x="268"/>
<layer name="Layer 0" h="355" w="600" z="0" y="287" x="631"/>
</layers>
Run Code Online (Sandbox Code Playgroud)
这是我的自制Xml类中的操作代码,它使用DocumentBuilderFactory来解析输入的Xml:
public static Xml parse(String xmlString)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = null;
//System.out.print(xmlString);
try
{
doc = dbf.newDocumentBuilder().parse(
new InputSource(new StringReader(xmlString)));
// Get root element...
Node rootNode = (Element) doc.getDocumentElement();
return getXmlFromNode(rootNode);
} catch (ParserConfigurationException e)
{
System.out.println("ParserConfigurationException in Xml.parse");
e.printStackTrace();
} catch (SAXException e)
{
System.out.println("SAXException in Xml.parse ");
e.printStackTrace();
} catch (IOException e)
{
System.out.println("IOException in Xml.parse");
e.printStackTrace();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它的上下文是:用于生成Photoshop类型图像处理应用程序的学校项目.正在使用.png和此xml文件的图层保存文件,以获取.zip文件中图层的位置等.我不知道压缩是否会增加一些神秘的额外字符.
感谢您的反馈.
Bri*_*new 13
如果你在编辑器中查看该文件,你会看到结束元素之后的内容(可能是空格),例如
</layers> <-- after here
Run Code Online (Sandbox Code Playgroud)
值得使用一个突出显示空白字符的工具来解决这个问题
$ cat -v -e my.xml
Run Code Online (Sandbox Code Playgroud)
将转储'不可打印的'字符.
希望这在某些方面对某人有帮助.有效的修复只是使用带子字符串的lastIndexOf().这是原位代码:
public void loadFile(File m_imageFile)
{
try
{
ZipFile zipFile = new ZipFile(m_imageFile);
ZipEntry xmlZipFile = zipFile.getEntry("xml");
byte[] buffer = new byte[10000];
zipFile.getInputStream(xmlZipFile).read(buffer);
String xmlString = new String(buffer);
Xml xmlRoot = Xml.parse(xmlString.substring(0, xmlString.lastIndexOf('>')+1));
for(List<Xml> iter = xmlRoot.getNestedXml(); iter != null; iter = iter.next())
{
String layerName = iter.element().getAttributes().getValueByName("name");
m_view.getCanvasPanel().getLayers().add(
new Layer(ImageIO.read(zipFile.getInputStream(zipFile.getEntry(layerName))),
Integer.valueOf(iter.element().getAttributes().getValueByName("x")),
Integer.valueOf(iter.element().getAttributes().getValueByName("y")),
Integer.valueOf(iter.element().getAttributes().getValueByName("w")),
Integer.valueOf(iter.element().getAttributes().getValueByName("h")),
Integer.valueOf(iter.element().getAttributes().getValueByName("z")),
iter.element().getAttributes().getValueByName("name"))
);
}
zipFile.close();
} catch (FileNotFoundException e)
{
System.out.println("FileNotFoundException in MainController.loadFile()");
e.printStackTrace();
} catch (IOException e)
{
System.out.println("IOException in MainController.loadFile()");
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
}
感谢所有贡献的人.我怀疑错误是由zip进程或使用byte []缓冲区引入的.任何进一步的反馈表示赞赏