解析XML文件时出现异常

时间:2014-07-20 14:43:16

标签: java xml encoding

当我从方法getIdFromDatabase调用来自我的XML数据库的get id但是向我显示exception [Fatal Error] :1:1: Content is not allowed in prolog.

致电方法getIdFromDatabase

nameLayer =getIdLayerFromDatabase("//Project/Layer[Name="+"'"+Name+"'"+"]/@idLayer","ProjectDataBase.xml");

java中的方法:

 public int getIdFromDatabase(String PathXPath, String Path) throws JAXBException {
            int maxid = -1, id = -1;
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder builder = domFactory.newDocumentBuilder();
                //***** exception here****************************** 
                Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(Path.getBytes("UTF-8"))));
                XPath xPath = XPathFactory.newInstance().newXPath();
                NodeList nl = (NodeList) xPath.evaluate(PathXPath, dDoc, XPathConstants.NODESET);
                for (int i = 0; i < nl.getLength(); i++) {
                    id = Integer.parseInt(nl.item(i).getNodeValue());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return id;
        }

XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<Project xmlns="http://www.example.org/ProjectDataBase" name="شئؤ" location="Projects//شئؤ//ProjectDataBase.xml" CreationDate="2014-07-20">
   <Layer idLayer="0">
      <Name>طبقة  1</Name>
   </Layer>
</Project>

1 个答案:

答案 0 :(得分:1)

问题在于您尝试解析路径而不是文件。改变这一行:

Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(Path.getBytes("UTF-8"))));

由:

Document dDoc = builder.parse(new FileInputStream(Path));