这对你来说很难。
我正在创建一个类项目,在那里我创建了一个点对点聊天程序,我遇到了这个问题:
当我打开聊天窗口时,没有问题。当我打开第二个窗口并尝试登录聊天时,我收到此错误:
**[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;
}
}
答案 0 :(得分:43)
问题是你之前有多个XML标头或噪音。
XML doc的典型开始......
<?xml version='1.0'?>
看起来像PI,但事实并非如此。如果你有一个额外的,或者如果你之前有一个BOM以外的任何东西,这就是你将得到的错误。
答案 1 :(得分:15)
我在weblogic上部署spring webapp时遇到了类似的问题。我们把第一行作为空白 在xml文件中。这导致XML解析失败并出现此错误。删除后,它工作了!!希望它对其他人来说也是有用的信息.. :)
答案 2 :(得分:11)
在您启动xml之前,有不需要的内容可能是其他嘈杂的东西的空间,即:
<?xml version='1.0'?>
确保在启动xml之前没有任何内容。这样可以解决问题, 一个相关的例子是:
答案 3 :(得分:6)
我遇到了同样的问题,我解决了以下问题。
以下代码导致错误。
<?xml version="1.0" encoding="UTF-8"?>
所以,我之前只是放了一个空格?&gt;。
<?xml version="1.0" encoding="UTF-8" ?>
在我这样做之后,没有更多的错误。
答案 4 :(得分: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>
答案 5 :(得分:2)
我明白了。我需要在创建每个新参与者后清除缓冲区。咄!!!
感谢您的帮助!!
答案 6 :(得分:2)
我最近正在研究Spring MVC启动项目示例,其中我使用了maven构建的工具。当我使用jetty运行我的服务器时,我得到了这个处理指令错误,我发现我的web.xml
在<xml>
标记之前有一个额外的标记,而是以<DOCTYPE>
标记开头。
所以我删除了以下标记,即开始标记
<!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
的开始标记,它解决了我的问题。
注意:请确保<?xml ...?>
标记前没有留下评论,标记,空格或任何不需要的字符。这将主要在解析xml文件时抛出这些类型的错误。
答案 7 :(得分:0)
实际上是因为不需要的内容,在我的情况下是因为我总是使用注释来理解代码,所以我在<!-- -->
&gt;
<?xml version='1.0'?
发表了评论
所以只需在这行之后添加评论并解决问题!