如何将XML字符串解析为Java对象?

时间:2014-08-08 04:42:19

标签: java xml web-services xml-parsing

我有一个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字符串中提取令牌

1 个答案:

答案 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