jjzjj

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

coder 2023-05-17 原文

这对你来说很难。

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

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

**[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;
    }
}

最佳答案

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

XML 文档的典型开头...

<?xml version='1.0'?>

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

关于java - "[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL] "is not allowed.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4235991/

有关java - "[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL] "is not allowed."的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

  10. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

随机推荐