我正试图将一个字符串解析为一个文档。字符串的内容是我从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();
}我错过了什么或者做错了什么?
提前谢谢。
发布于 2018-09-07 18:06:49
我犯了一个大错误:我试图解析byte[]数据,执行new String(content)解决了我的问题!
https://stackoverflow.com/questions/52227401
复制相似问题