SAXParseException - 文档结构

时间:2012-11-20 18:45:58

标签: java xml dom saxparser

我正在编写一个发送/接收xml的应用。

使用DOM生成消息并定期发送到服务器(2秒内一次)。在获取某些消息时(它取决于某些参数,但对于不同的启动而言是不变的)服务器会响应错误:XML document structures must start and end within the same entity - 可能会收到消息的结尾。有时错误会连续出现,有时会与正常的消息混在一起。

正确形成消息(否则错误可能是从开始)。我想,在某种程度上它与消息长度有关;它休息时约有9800个符号。

我还发现了一个类似错误的帖子:SAXParseException: XML document structures must start and end within the same entity,但它与我的不同。

这里有一些代码,可能是我做错了。

生成文档类:

public class DOMConstructor {

private Element actions;
Document document = null;

DOMConstructor (String key) throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    document = documentBuilder.newDocument();
    Element rootElement = document.createElement("request");
    document.appendChild(rootElement);


    Element token = document.createElement("token");
    token.appendChild(document.createTextNode(key));
    rootElement.appendChild(token);


    Element actions = document.createElement("actions");
    rootElement.appendChild(actions);

    this.actions = actions;
}


public StreamResult getResultXml (OutputStream out) throws TransformerException, FileNotFoundException {

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    DOMSource domSource = new DOMSource(document);

    StreamResult streamResult = new StreamResult(out);
    transformer.transform(domSource, streamResult);

    return streamResult;
}


protected void addAction (String fromId, String toId, String droids_num) {      
    Element action = document.createElement("action");
    actions.appendChild(action);

    Element from = document.createElement("from");
    from.appendChild(document.createTextNode(fromId));
    action.appendChild(from);

    Element to = document.createElement("to");
    to.appendChild(document.createTextNode(toId));
    action.appendChild(to);

    Element units = document.createElement("unitscount");
    units.appendChild(document.createTextNode(droids_num));
    action.appendChild(units);
}       
}

发送xml:

public void sendData (XMLData xml) throws UnknownHostException, IOException, TransformerException, ParserConfigurationException, SAXException {
    conn = new Socket(address, port);       
    OutputStream out = new BufferedOutputStream(conn.getOutputStream());
    xml.sendData(out, true);

}

0 个答案:

没有答案
相关问题