解析字符串到文档

时间:2018-09-07 17:49:33

标签: java android xml

我正在尝试将字符串解析为文档。字符串的内容是我从SIP消息中获得的XML数据。

我尝试这样做:

DocumentBuilder db;
Document pidf;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
db = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( content ));

pidf = db.parse(is);

但是我得到这个错误:

org.xml.sax.SAXParseException: Unexpected token (position:TEXT [B@fd41b3b@1:11 in java.io.StringReader@83dc258) 

我使用Log.d()查看字符串的内容,并且可以看到以下内容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><presence xmlns="urn:ietf:params:xml:ns:pidf" xmlns:dm="urn:ietf:params:xml:ns:pidf:data-model" xmlns:iot="urn:uma-etsit-ic:internet-of-things" xmlns:ts="PIDF" entity="pres:mymail@uma.es:5050"><tuple id="qoica32"><status><basic>open</basic></status><ts:timed-status from="2018-09-07T19:30:30.119+02:00" until="2018-09-07T20:30:30.129+02:00"><basic>close</basic></ts:timed-status></tuple><dm:device id="dtemp1"><iot:tecnologia><iot:802-11/></iot:tecnologia><iot:bateria>100</iot:bateria></dm:device><dm:person><iot:sensor><iot:temperatura/></iot:sensor><iot:unindad><iot:celsius/></iot:unindad><iot:valor>29.3</iot:valor></dm:person></presence>

我将其复制并粘贴到验证器网页,并通过了验证。

由于错误输出,我认为解析时可能是格式错误,因此我尝试添加is.setEncoding("UTF-8")来解决它,但仍然出现相同的错误。

我是通过Java程序上的XML创建的字符串,这是代码:

public String getContent() {

    StringWriter sw = new StringWriter();

    try {

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(pidfContent), new StreamResult(sw));

        return sw.toString();
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(PIDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        Logger.getLogger(PIDF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return sw.toString();

}

我在Android中缺少什么或做错了什么?

谢谢。

1 个答案:

答案 0 :(得分:0)

我犯了一个大错误:我试图解析byte []数据,执行new String(content)解决了我的问题!

相关问题