解析Java StAX XML中的问题

时间:2014-02-26 19:36:28

标签: java swing xml-parsing stax

我一直在寻找这个问题的解决方案而一无所获。我正在创建一个关于Java TCP / IP套接字的简单聊天作为赋值,我在创建包含字母åäö的XML字符串时遇到了问题。

假设我传递带有字段

的XMLObject

name =“Server”,color =“#FF0000”text =“åäö”

解析器返回的生成的xmlstring将是

<?xml version="1.0"?><message sender="Server"><text color="#FF0000”>???</text></message>

åäö变成了???任何的想法?谢谢!

**更新** 好的,所以我刚刚意识到从JTextArea获取一些文本时会出现问题。

如果我运行此代码:

package self.edu.javaprojekt.view;

import self.edu.javaprojekt.model.XMLObject;
import self.edu.javaprojekt.model.XMLParser;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        XMLObject object = new XMLObject();
        object.setColor("#FF0000");
        object.setSender("Server");
        object.setText("åäö");
        String parsed = XMLParser.parse(object);
        System.out.println(parsed);
        System.out.println(XMLParser.parse(parsed));

    }

}

我得到了正确的结果:

<?xml version="1.0" encoding="UTF-8"?><message sender="Server"><text color="#FF0000">åäö</text></message>
XMLObject [sender=Server, text=åäö, color=#FF0000]

但有文字区域。在以下方法中返回的文本将添加到XMLObject,然后发送以进行解析。

public String readAndClearMessageArea() {
        String text = messageTextArea.getText();
        appendToPane("\n" + controller.getName() + ": " + text, controller.getColor());
        messageTextArea.setText("");
        return text;
    }

我得到了奇怪的结果。有什么新想法吗?谢谢!

这是解析器

package self.edu.javaprojekt.model;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Iterator;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class XMLParser {
    public static final String MESSAGE_TAG = "message";
    public static final String SENDER_TAG = "sender";
    public static final String TEXT_TAG = "text";
    public static final String COLOR_TAG = "color";
    public static final String DISCONNECT_TAG = "disconnect";
    public static final String ENCRYPTED_TAG = "encrypted";
    public static final String ENCRYPTED_TYPE_TAG = "type";
    public static final String KEY_REQUEST_TAG = "keyrequest";

    public static String parse(XMLObject object) {
        // create an XMLOutputFactory
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        // create XMLEventWriter
        XMLEventWriter eventWriter;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String xmlString = "";
        try {
            eventWriter = outputFactory.createXMLEventWriter(out);

            // create an EventFactory
            XMLEventFactory eventFactory = XMLEventFactory.newInstance();
            //XMLEvent end = eventFactory.createDTD("\n");
            //XMLEvent tab = eventFactory.createDTD("\t");
            // create and write Start Tag
            StartDocument startDocument = eventFactory.createStartDocument("UTF-8");
            eventWriter.add(startDocument);

            // create message open tag
            //eventWriter.add(end);
            StartElement messageStartElement = eventFactory.createStartElement(
                    "", "", MESSAGE_TAG);
            eventWriter.add(messageStartElement);
            eventWriter.add(eventFactory.createAttribute(SENDER_TAG,
                    object.getSender()));
            //eventWriter.add(end);

            // create the text
            //eventWriter.add(tab);
            StartElement textStartElement = eventFactory.createStartElement("",
                    "", TEXT_TAG);
            eventWriter.add(textStartElement);
            eventWriter.add(eventFactory.createAttribute(COLOR_TAG,
                    object.getColor()));

            Characters characters = eventFactory.createCharacters(object.getText());
            eventWriter.add(characters);

            //eventWriter.add(tab);
            eventWriter.add(eventFactory.createEndElement("", "", TEXT_TAG));
            //eventWriter.add(end);

            eventWriter.add(eventFactory.createEndElement("", "", MESSAGE_TAG));
            //eventWriter.add(end);
            eventWriter.add(eventFactory.createEndDocument());
            eventWriter.close();
            xmlString = out.toString("UTF-8");
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return xmlString;
    }

    @SuppressWarnings("unchecked")
    public static XMLObject parse(String string) {
        XMLObject object = null;
        try {
            // First, create a new XMLInputFactory
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            // Setup a new eventReader
            InputStream in;
            if (!string.equals("")) {
                in = new ByteArrayInputStream(Charset.forName("UTF-8")
                        .encode(string).array());
            } else {
                in = new FileInputStream("xmltest.txt");
            }
            XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

            // read the XML document
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                if (event.isStartElement()) {
                    StartElement startElement = event.asStartElement();
                    // If we have a message
                    if (startElement.getName().getLocalPart()
                            .equals(MESSAGE_TAG)) {
                        object = new XMLObject();
                        // We read the attributes from this tag and add the
                        // sender
                        // attribute to our object
                        Iterator<Attribute> attributes = startElement
                                .getAttributes();
                        while (attributes.hasNext()) {
                            Attribute attribute = attributes.next();
                            if (attribute.getName().getLocalPart()
                                    .equals(SENDER_TAG)) {
                                object.setSender(attribute.getValue());
                            }

                        }
                    }

                    if (startElement.getName().getLocalPart().equals(TEXT_TAG)) {
                        // We read the attributes from this tag and add the
                        // color
                        // attribute to our object
                        Iterator<Attribute> attributes = startElement
                                .getAttributes();
                        while (attributes.hasNext()) {
                            Attribute attribute = attributes.next();
                            if (attribute.getName().getLocalPart()
                                    .equals(COLOR_TAG)) {
                                object.setColor(attribute.getValue());
                            }

                        }
                        // And then get the text
                        event = eventReader.nextEvent();
                        object.setText(event.asCharacters().getData());
                        continue;
                    }
                }
                // If we reach the end of the message, return the object
                if (event.isEndElement()) {
                    EndElement endElement = event.asEndElement();
                    if (endElement.getName().getLocalPart().equals(MESSAGE_TAG)) {
                        return object;
                    }
                }

            }
        } catch (XMLStreamException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

这是包含xml值的类

package self.edu.javaprojekt.model;

public class XMLObject {
    private String sender, text, color;

    public String getSender() {
        return sender;
    }

    public String getText() {
        return text;
    }

    public String getColor() {
        return color;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "XMLObject [sender=" + sender + ", text=" + text + ", color="
                + color + "]";
    }

}

1 个答案:

答案 0 :(得分:0)

之前我已经看到过,您可以使用不同的编码来查看哪个适合您。但是尝试ISO-8859-1或UTF-16。不确定您需要哪种编码。