我有一个XML字符串,我从Web服务获得响应。我想解析它并将其转换为Java对象。请帮我解决一下。我尝试过使用各种库但失败了。所有都有例外。
XML 字符串:
<LOGINRESPONSE xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Message="Login Successful"
Token="SFTT67FGHUU" DataFormat="CSV" Header="true" Suffix="true"
xmlns="http://ws.eoddata.com/Data" />
我使用的代码是:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(
"http://<webservice URL>/Login?Username=<username>&Password=<password>");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpget, responseHandler);
System.out.println(response);
try (ByteArrayInputStream bais = new ByteArrayInputStream(response.getBytes())) {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bais);
System.out.println(doc);
} catch (Exception exp) {
exp.printStackTrace();
}
但是文档将以null
的形式出现。我想从xml字符串中提取令牌
答案 0 :(得分:1)
您应该能够将String
打包到ByteArrayInputStream
并将其传递给DocumentBuilder
,例如......
String text = "<LOGINRESPONSE xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Message=\"Login Successful\" Token=\"SFTT67FGHUU\" DataFormat=\"CSV\" Header=\"true\" Suffix=\"true\" xmlns=\"http://ws.eoddata.com/Data\" />";
try (ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes())) {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bais);
} catch (ParserConfigurationException | SAXException | IOException exp) {
exp.printStackTrace();
}
<强>更新... 强>
要提取属性,您可以使用类似......
的内容NamedNodeMap atts = doc.getDocumentElement().getAttributes();
Node node = atts.getNamedItem("Message");
System.out.println("Message = " + node.getTextContent());
打印......
Message = Login Successful