org.xml.sax.SAXParseException根元素后面的文档中的标记必须格式正确

时间:2018-01-16 15:50:11

标签: java xml

我知道有一些类似的线程,但没有一个对我有任何帮助,我正在尝试通过Java创建XML文件,但我在这条线上不断看到这个错误 doc = db.parse(is); 有人可以告诉我哪里出错了吗? 错误: -

Severe:   [Fatal Error] :2:2: The markup in the document following the root element must be well-formed.
Severe:   org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 2; The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
at com.digivote.digivote.XmlServlet.doPost(XmlServlet.java:194)

我的代码:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");        
    String level = request.getParameter("level");
    String add = request.getParameter("add");
    String addCat = request.getParameter("addCat");
    String addQuestions = request.getParameter("addQuestion");
    String add_multiChoice = request.getParameter("add_multiChoice");

    try 
    {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

          // root elements
        Document doc = db.newDocument();
        Element rootElement = doc.createElement("XML");
        doc.appendChild(rootElement);

        /***** GeneratedSet ****/
        Element genSet = doc.createElement("GeneratedSet");
        rootElement.appendChild(genSet);

        Attr genDate = doc.createAttribute("genDate");
        genDate.setValue("11/01/2018");
        genSet.setAttributeNode(genDate);

        Attr genBy = doc.createAttribute("genBy");
        genBy.setValue("Tom Jones");
        genSet.setAttributeNode(genBy);

        Attr lev = doc.createAttribute("level");
        lev.setValue(level);
        genSet.setAttributeNode(lev);

        /****** Questions *****/
        Element questions = doc.createElement("Questions");
        genSet.appendChild(questions);

        Attr noq = doc.createAttribute("Questions");
        noq.setValue(addQuestions);
        questions.setAttributeNode(noq);

        Attr type = doc.createAttribute("Type");
        type.setValue(add);
        questions.setAttributeNode(type);

        /****** Question *****/
        int numOfQues = Integer.parseInt(addQuestions) ;
        int leve = Integer.parseInt(level) ;

        String retXML = null;
        if(add != null){
            InputSource is = new InputSource();
            genMaths gm = new genMaths();
            retXML = gm.additionQ(leve, 2, numOfQues, 0);
            is.setCharacterStream(new StringReader(retXML));
            doc = db.parse(is);
            //doc = db.parse(new InputSource(new StringReader(is.toString())));
        }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("C:\\Users\\xxxx\\Documents\\XML Files\\RandomQuestions.xml"));

            transformer.transform(source, result);
            System.out.println("File saved!");

    } catch (ParserConfigurationException | TransformerException pce) {} catch (SAXException ex) {
        Logger.getLogger(XmlServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
   }
 }

retXML: -

        public String forwardQ ( int level, int operands, int operation, int questions, int type )
    {
        StringBuffer retXML = new StringBuffer ();
        float operand = 0;
        float answer = 0;
        int minVal = (int)getLevelMin(level);
        int maxVal = (int)getLevelMax(level);

        String addSign = "";

        for ( int j = 0; j < questions; j++ )
        {
            retXML.append("<Question Text='");
            addSign = "";

            if ( operation == 1 )
            {
                answer = 0;
            }
            else
            {
                answer = 1;
            }

            for ( int i = 0; i < operands; i++ )
            {
                operand = randNum(minVal, maxVal);
                if ( operation == 1 )
                {
                    answer = answer + operand;
                }
                else
                {
                    answer = answer * operand;
                }
                retXML.append( addSign + operand );
                if ( operation == 1 )
                {
                    addSign = " + ";
                }
                else
                {
                    addSign = " x ";
                }
            }

            if ( type == 1 )
            {
                retXML.append("' Answer='"+ answer + "'>");            
            }
            else
            {
                retXML.append(createMultiChoice(answer));
            }
            retXML.append("</Question>" + System.getProperty("line.separator"));
        }

        return ( retXML.toString() );
    }

    public String additionQ ( int level, int operands, int questions, int type )
    {
        return ( forwardQ ( level, operands, 1, questions, type ) );
    }

1 个答案:

答案 0 :(得分:5)

从您的代码中看,您的XML最终会以

结尾
<Question ...></Question>
<Question ...></Question>

XML文档中不能包含多个根元素。您可以尝试将所有Question元素包装在根元素中,例如

<Questions>
    <Question ...></Question>
    <Question ...></Question>
</Questions>