我无法解析这个:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<response>
<status>OK</status>
<time>2012-12-18 21:55</time>
</response>
按代码:
InputStream is=sock.getInputStream();
String sa="";
int cc;
while((cc=is.read())!=-1){
sa+=(char) cc;
}
ByteArrayInputStream sr=new ByteArrayInputStream(sa.getBytes());
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(sr);
sr
是放置它的String
。怎么可能?当我使用doc.getNodeName
时,我得到null。
答案 0 :(得分:0)
还有另一个可以解析您的输入流。尝试这个,你将有一个完整的控制
parsing xml file using java for -- android based application
或者
public class Tester {
String getString() throws IOException, ParserConfigurationException, SAXException {
InputStream inputStream = getClass().getResourceAsStream("input.xml");
String sa = "";
int cc;
while((cc = inputStream.read()) != -1) {
sa += (char) cc;
}
ByteArrayInputStream sr = new ByteArrayInputStream(sa.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(sr);
Node node=doc.getDocumentElement().getFirstChild();
String data=node.getNodeName();
return data;
}
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
Tester t = new Tester();
System.out.println(t.getString());
}
}