Java “[致命错误] :1:120:不允许匹配“[xX][mM][lL]”的处理指令目标。”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4235991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:52:40  来源:igfitidea点击:

"[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL]" is not allowed."

javaxml

提问by novicePrgrmr

Here's a tough one for you.

这对你来说很难。

I am working on a class project where I create a peer-to-peer chat program and I have this problem:

我正在做一个班级项目,在那里我创建了一个点对点聊天程序,但我遇到了这个问题:

When I open up a chat window, no problems. When I open up a second window and try and login to the chat, I get this error:

当我打开聊天窗口时,没有问题。当我打开第二个窗口并尝试登录聊天时,出现此错误:

**[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL]" is not allowed.
org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
        at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249)
        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
        at chatter2.Chatter.process(Chatter.java:240)
        at chatter2.Chatter.run(Chatter.java:222)
        at java.lang.Thread.run(Thread.java:680)**

I am pretty sure it has something to do with how my code is creating the XML for participants.

我很确定这与我的代码为参与者创建 XML 的方式有关。

Here is all the code I have written:

这是我写的所有代码:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on Nov 10, 2010, 2:11:39 PM
 */
package chatter2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import java.io.StringReader;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

/**
 *
 * @author ericrea
 */
public class Chatter extends javax.swing.JFrame implements Runnable {

    PrintWriter out = null;
    BufferedReader in = null;
    boolean running = true;
    String partName = "";
    String chatHist = "";

    /** Creates new form NewJFrame */
    public Chatter() {
        initComponents();
        Server server = new Server();
        server.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        msgText = new javax.swing.JTextArea();
        send = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        chatText = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        userName = new javax.swing.JTextField();
        IPaddress = new javax.swing.JTextField();
        PortField = new javax.swing.JTextField();
        Login = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        chatMembers = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(550, 550));

        jPanel1.setLayout(new java.awt.GridLayout(1, 0));

        msgText.setColumns(20);
        msgText.setRows(5);
        msgText.setPreferredSize(new java.awt.Dimension(240, 24));
        msgText.setRequestFocusEnabled(false);
        jPanel1.add(msgText);

        send.setText("Send");
        send.setPreferredSize(new java.awt.Dimension(100, 29));
        send.setRolloverEnabled(true);
        send.setSelected(true);
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });
        jPanel1.add(send);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

        jPanel2.setLayout(new java.awt.GridLayout(1, 0));

        chatText.setBackground(new java.awt.Color(0, 255, 204));
        chatText.setColumns(20);
        chatText.setRows(5);
        jPanel2.add(chatText);

        getContentPane().add(jPanel2, java.awt.BorderLayout.LINE_END);

        jPanel3.setLayout(new java.awt.GridLayout(1, 0));

        userName.setText("UserName");
        jPanel3.add(userName);

        IPaddress.setText("127.0.0.1");
        IPaddress.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                IPaddressActionPerformed(evt);
            }
        });
        jPanel3.add(IPaddress);

        PortField.setText("44640");
        jPanel3.add(PortField);

        Login.setText("Login");
        Login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginActionPerformed(evt);
            }
        });
        jPanel3.add(Login);

        jButton1.setText("Logout");
        jPanel3.add(jButton1);

        getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_START);

        chatMembers.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        chatMembers.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        chatMembers.setPreferredSize(new java.awt.Dimension(80, 87));
        jPanel4.add(chatMembers);

        getContentPane().add(jPanel4, java.awt.BorderLayout.LINE_START);

        pack();
    }// </editor-fold>                        

    private void LoginActionPerformed(java.awt.event.ActionEvent evt) {                                      

        try {
            Socket s = new Socket(IPaddress.getText(), Integer.parseInt(PortField.getText()));
            out = new PrintWriter(s.getOutputStream());
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            new Thread(this).start();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element root = doc.createElement("login");
            doc.appendChild(root);
            root.appendChild(doc.createTextNode(userName.getText()));

            TransformerFactory fact = TransformerFactory.newInstance();
            Transformer trans = fact.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult sResult = new StreamResult(out);
            trans.transform(source, sResult);
            out.println("\n");

            out.flush();
        } catch (Exception e) {
        }
    }                                     

    private void IPaddressActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                     

    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Chatter().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextField IPaddress;
    private javax.swing.JButton Login;
    private javax.swing.JTextField PortField;
    private javax.swing.JList chatMembers;
    private javax.swing.JTextArea chatText;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTextArea msgText;
    private javax.swing.JButton send;
    private javax.swing.JTextField userName;
    // End of variables declaration                   

    public void run() {

        String buffer = "";
        while (running) {
            try {

                String line = in.readLine();
                System.out.println(line);

                if (line.equals("")) {

                    process(buffer);
                } else {

                    buffer = buffer + line;
                }
            } catch (Exception e) {
            }

        }
    }

    public void process(String buffer) {

        try {

            System.out.println("buffer in process is " + buffer);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.parse(new StringBufferInputStream(buffer)); //new InputSource(new StringReader(buffer))
            Element root = doc.getDocumentElement();



            if (root.getNodeName().equals("message")) {
                chatHist = chatHist + root.getTextContent() + "\n";
                newMessage();

            }
            else if (root.getNodeName().equals("participants")) {
                DefaultListModel partNames = new DefaultListModel(); 
                for(int i = 0; i < root.getChildNodes().getLength(); i++){
                     //partName = partName + root.getChildNodes().item(i).getTextContent() + "/n";
                     partNames.addElement(root.getChildNodes().item(i).getTextContent());

                }
                chatMembers.setModel(partNames);

            }

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





    }

    public void cleanStop() {
    }

    public void newMessage() {
        chatText.setText(chatHist);
    }
}


    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chatter2;


import java.io.*;
import java.net.*;
import java.util.LinkedList;
import java.util.List;
import org.w3c.dom.Document;


/**
 *
 * @author ericrea
 */
public class Server extends Thread {

    private ServerSocket ss = null;
    private List<Participant> parts = new LinkedList<Participant>();

    public Server(){
        try{
        ss = new ServerSocket(44640);
        }catch(Exception e){e.printStackTrace();
        }

    }

    @Override
    public void run() {

      //add this into a while loop
            while (true){
                 try{
            Socket s = ss.accept();
            Participant p = new Participant(this, s);
            p.start();
            getParts().add(p);
            }
            catch(Exception e){
            e.printStackTrace();}





//            System.out.println(" Got a client socket connection");
//            PrintWriter out =  new PrintWriter(s.getOutputStream());
//            BufferedReader in =  new BufferedReader(new InputStreamReader(s.getInputStream()));
//            out.println("hey there, want to chat");
//            out.flush();
//            String line = in.readLine();
//            System.out.println("Client said: " + line);


        }

    }
    public void message(Document doc){
        for (Participant p: getParts()){
            p.newMessage(doc);
        }
    }

    public void newParticipants(){
       int counter = 1;
        for(Participant p: getParts()){
            //System.out.println(counter + " time through the loop");
            counter++;
            p.newParticipant();
        }


    }

    public void cleanStop(){

    }
    public void logout(Participant p){
        parts.remove(p);
        newParticipants();
    }

    /**
     * @return the ss
     */
    public ServerSocket getSs() {
        return ss;
    }

    /**
     * @param ss the ss to set
     */
    public void setSs(ServerSocket ss) {
        this.ss = ss;
    }

    /**
     * @return the parts
     */
    public List<Participant> getParts() {
        return parts;
    }

    /**
     * @param parts the parts to set
     */
    public void setParts(List<Participant> parts) {
        this.parts = parts;
    }

}


    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatter2;

import java.io.*;
import java.util.*;
import java.net.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

/**
 *
 * @author ericrea
 */
public class Participant extends Thread {

    Server server = null;
    Socket client = null;
    PrintWriter out = null;
    BufferedReader in = null;
    boolean running = true;
    private String partName = null;

    public Participant(Server server, Socket client) throws IOException {
        this.client = client;
        this.server = server;
        out = new PrintWriter(client.getOutputStream());
        in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    }

    //run and actONMessage will be in the chatter class as well
    @Override
    public void run() {


            String buffer = "";
            while (running) {
                try {
                    String line = in.readLine();

                    if (line.equals("")) {

                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = factory.newDocumentBuilder();
                        Document doc = docBuilder.parse(new InputSource(new StringReader(buffer)));
                        actOnMessage(doc);
                    } else {
                        buffer = buffer + line;
                    }

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

    }

    public void actOnMessage(Document doc) {

        Element root = doc.getDocumentElement();


        if (root.getNodeName().equals("login")) {
            setPartName(root.getTextContent());

            this.login();
        } else if (root.getNodeName().equals("message")) {
            message(doc);
        } else if (root.getNodeName().equals("logout")) {
            this.logout();
        }

    }

    public void message(Document doc) {
        server.message(doc);

    }

    public void login() {
        server.newParticipants();
    }

    public void logout() {
        server.logout(this);
    }

    public void newMessage(Document doc) {
        out.println(/*String version of the xml*/);
    }

    public void newParticipant() {
        try {

            List<Participant> partList = server.getParts();

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element root = doc.createElement("participants");
            doc.appendChild(root);

            for (Participant k : partList) {
                Element root1 = doc.createElement("participant");
                root.appendChild(root1);
                root1.appendChild(doc.createTextNode(k.getPartName()));

            }

            TransformerFactory fact = TransformerFactory.newInstance();
            Transformer trans = fact.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult sResult = new StreamResult(out);
            trans.transform(source, sResult);
            out.println("\n");

            out.flush();
        } catch (Exception e) {
        }
    }

    public void cleanStop() {
    }

    public void getParticipantName() {
    }

    /**
     * @return the partName
     */
    public String getPartName() {
        return partName;
    }

    /**
     * @param partName the partName to set
     */
    public void setPartName(String partName) {
        this.partName = partName;
    }
}

采纳答案by novicePrgrmr

I figured it out. I needed to clear the buffer after every new participant is created. duh!!!

我想到了。创建每个新参与者后,我需要清除缓冲区。呸!!!

thanks for the help!!

谢谢您的帮助!!

回答by bmargulies

The problem is that you have more than one XML header or noise before one.

问题是您在一个之前有多个 XML 标头或噪音。

The typical start of an XML doc...

XML 文档的典型开头...

<?xml version='1.0'?>

looks like a PI, but isn't. If you have an extra, or if you have anything other than a BOM before one, that's the error you'll get.

看起来像一个 PI,但不是。如果你有一个额外的,或者如果你在一个之前有一个 BOM 以外的任何东西,那就是你会得到的错误。

回答by Blundell

Another answer to this is using XML within XML will break you need to not parse the inner XML and use the CDATA tag see here:

对此的另一个答案是在 XML 中使用 XML 会破坏您不需要解析内部 XML 并使用 CDATA 标记,请参见此处:

http://www.w3schools.com/xml/xml_cdata.asp

http://www.w3schools.com/xml/xml_cdata.asp

ie:

IE:

<?xml version='1.0'?>
  <sometag>
  <![CDATA[
    <?xml version='1.0'?>
    <nonParsedTag></nonParsedTag>
  ]]></sometag>

回答by Gopinath M.R

I faced similar issue on deploying a spring webapp on weblogic. We had first line as blank in xml file. This caused XML parsing failure with this error. After removing this, it worked!! Hope it is useful info for others too.. :)

我在 weblogic 上部署 spring webapp 时遇到了类似的问题。我们在 xml 文件中的第一行是空白的。这导致 XML 解析失败并出现此错误。删除后,它起作用了!!希望它对其他人也有用.. :)

回答by Forhad

There is unwanted content may be space of other noisy thing before the starting of you xml namely :

在你 xml 开始之前,有不需要的内容可能是其他嘈杂的空间,即:

<?xml version='1.0'?>

Make sure there is nothing before the starting of your xml . This will solve the problem , One related example is :

确保在 xml 开始之前没有任何内容。这将解决问题,一个相关的例子是:

related reference

相关参考

回答by Zin Win Htet

I encountered the same problem and I solved like following.

我遇到了同样的问题,我解决了如下。

Following code cause error.

以下代码导致错误。

<?xml version="1.0" encoding="UTF-8"?>

So, I simply put a space before ?>.

所以,我只是在 ?> 之前放了一个空格。

<?xml version="1.0" encoding="UTF-8" ?>

After I did like that, there was no more error.

在我这样做之后,没有更多的错误。

回答by AngieF

It is actually because of unwanted content, in my case it was because I always use comments for understanding the code later so I had comments with <!-- -->before the <?xml version='1.0'?>

这实际上是因为不需要的内容,在我的情况下是因为我总是使用注释来理解代码,所以我<!-- --><?xml version='1.0'?>之前有注释

So just put comments afterthis line and Problem Solved!

因此,只需此行发表评论并解决问题!

回答by Lucky

I recently was working on a Spring MVC startup project sample where I used maven built tool. When I run my server using jetty I got this processing instruction error and I found that my web.xmlwas having an extra tag before the <xml>tag and it started with the <DOCTYPE>tag instead.

我最近正在研究一个 Spring MVC 启动项目示例,其中使用了 maven 构建的工具。当我使用 jetty 运行我的服务器时,我收到了这个处理指令错误,我发现我web.xml在标签之前有一个额外的<xml>标签,而是以<DOCTYPE>标签开头。

So I removed the below tag which was the start tag,

所以我删除了下面的标签,这是开始标签,

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >

and had the below tag,

并有以下标签,

<?xml version="1.0" encoding="UTF-8"?>

as the start tag of my web.xmland it solved my issue.

作为我的开始标签,web.xml它解决了我的问题。

Note: Please ensure there is no comments, tags, free spaces or any unwanted characters left before the <?xml ...?>tag. This will mainly throw these type of error while parsing the xml files.

注意:请确保标签前没有任何评论、标签、可用空格或任何不需要的字符<?xml ...?>。这将主要在解析 xml 文件时抛出这些类型的错误。