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

Posted

技术标签:

【中文标题】“[致命错误]:1:120:不允许匹配“[xX][mM][lL]”的处理指令目标。” [复制]【英文标题】:"[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL]" is not allowed." [duplicate] 【发布时间】:2011-05-13 06:26:02 【问题描述】:

这对你来说很难。

我正在创建一个点对点聊天程序的课堂项目,但我遇到了这个问题:

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

**[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)**

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

这是我写的所有代码:

    /*
 * 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;
    

【问题讨论】:

你包含的chatter2包出现错误;我们不知道这是在做什么,这使得查看您的代码变得无关紧要。 Chatter2 是项目名称。 解决了导致此错误消息的 三个 可能原因中的每一个的解决方法here 【参考方案1】:

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

XML 文档的典型开头...

<?xml version='1.0'?>

看起来像 PI,但不是。如果您有一个额外的,或者如果您在一个之前有 BOM 以外的任何其他内容,这就是您将得到的错误。

【讨论】:

PI 是您的错误消息中的处理指令。 我刚刚发现,如果我在登录聊天者之前启动所有聊天窗口,那么我不会收到该错误。任何线索为什么? Eric,你不要再要求我们从头调试你的程序,而是从底层开始理解它的行为。 这就是我的问题,我在 标签之前有一个导入。谢谢!【参考方案2】:

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

谢谢你的帮助!!

【讨论】:

【参考方案3】:

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

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

即:

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

【讨论】:

【参考方案4】:

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

【讨论】:

【参考方案5】:

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

<?xml version='1.0'?>

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

related reference

【讨论】:

【参考方案6】:

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

以下代码导致错误。

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

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

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

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

【讨论】:

【参考方案7】:

实际上是因为不需要的内容,就我而言,这是因为我以后总是使用 cmets 来理解代码,所以我在 &lt;?xml version='1.0'? 之前使用了带有 &lt;!-- --&gt; 的 cmets>

所以只需将 cmets 放在这一行之后,问题就解决了!

【讨论】:

【参考方案8】:

我最近正在研究一个 Spring MVC 启动项目示例,其中我使用了 maven 构建工具。当我使用码头运行我的服务器时,我得到了这个处理指令错误,我发现我的web.xml&lt;xml&gt; 标记之前有一个额外的标记,它以&lt;DOCTYPE&gt; 标记开始。

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

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

并且有下面的标签,

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

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

注意:请确保&lt;?xml ...?&gt; 标记之前没有任何 cmets、标签、空闲空格或任何不需要的字符。这主要会在解析xml文件时抛出这些类型的错误。

【讨论】:

以上是关于“[致命错误]:1:120:不允许匹配“[xX][mM][lL]”的处理指令目标。” [复制]的主要内容,如果未能解决你的问题,请参考以下文章

Python 正确有效地获取 DBUS 对象路径(例如 /org/bluez/dev_XX_XX_XX_XX_XX_XX/playerY)

如何使用 IP 范围引用所有 IP,例如XX.XX.XX.XX / 24 [关闭]

HTTPConnectionPool(host='xx.xx.xx.xx', port=xx): Max retries exceeded with url:(Caused by Co

微信小程序时钟(xx年xx月xx日xx:xx格式)

Zabbix聚合检测

HTTP的response code 1xx,2xx,3xx,4xx,5xx分别代表什么