【问题标题】:How to parse an XML String into Java Object?如何将 XML 字符串解析为 Java 对象?
【发布时间】:2023-03-28 23:02:01
【问题描述】:

我有一个来自 Web 服务的响应作为响应的 XML 字符串。我想解析它并将其转换为 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();
}

但是 doc 以 null 的身份出现。我想从 xml 字符串中提取令牌

【问题讨论】:

  • “一些例外”?哪个图书馆/-ies?什么例外?首先要注意的一点是,由于元素的不寻常大写,大多数数据绑定库(如 JAXB 或 Jackson 的 XML 模块)将需要覆盖(通常是注解)来将 XML 元素映射到 Java 属性。
  • 在尝试使用 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("XML String") 我得到这个异常:java.net.MalformedURLException: no protocol: w3.org/2001/XMLSchema" xmlns:xsi="w3.org/2001/XMLSchema-instance" Message="登录成功" Token="021D29TDDPEG" DataFormat="CSV" 标头="true" 后缀="true" xmlns="ws.eoddata.com/Data" />

标签: java xml web-services xml-parsing


【解决方案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

【讨论】:

  • 当我尝试这个时,我得到 doc 为空。
  • 真的,我得到了[#document: null](使用System.out.println(doc);),它说Document 已成功创建...
  • 如何从 XML 字符串中提取令牌
  • 这是一个不错的改变……我的意思是,当然是这样的;)
猜你喜欢
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多