首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串解析为文档

将字符串解析为文档
EN

Stack Overflow用户
提问于 2018-09-07 17:49:33
回答 1查看 74关注 0票数 0

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

我试着这样做:

代码语言:javascript
复制
DocumentBuilder db;
Document pidf;

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

pidf = db.parse(is);

但我知道这个错误:

代码语言:javascript
复制
org.xml.sax.SAXParseException: Unexpected token (position:TEXT [B@fd41b3b@1:11 in java.io.StringReader@83dc258) 

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

代码语言:javascript
复制
<?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创建了这个字符串,这是代码:

代码语言:javascript
复制
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();

}

我错过了什么或者做错了什么?

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-09-07 18:06:49

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52227401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档