解析响应xml并计算CDATA中的XML元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析响应xml并计算CDATA中的XML元素相关的知识,希望对你有一定的参考价值。
我有一个代码,我解析响应XML并计算元素的出现。有没有办法可以在响应中解析CDATA并计算CDATA中的元素。
我目前用于解析XML的代码。
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(response.toString())));
NodeList list = doc.getElementsByTagName("RESPONSE");
System.out.println("Total : " + list.getLength());
我需要解析的示例XML,
<RESPONSE><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<ID>
<EMAIL>xxx@yyy</EMAIL>
<EMAIL>klihf@kjf</EMAIL>
<EMAIL>ddd@fff</EMAIL>
<EMAIL>@ddd</EMAIL>
</ID>
]]></RESPONSE>
谢谢
答案
RESPONSE标记之间的所有内容都将被视为字符串。尝试:
public class Main {
public static void main(String... args) {
String response = "<RESPONSE><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
" +
"<ID>
" +
" <EMAIL>xxx@yyy</EMAIL>
" +
" <EMAIL>klihf@kjf</EMAIL>
" +
" <EMAIL>ddd@fff</EMAIL>
" +
" <EMAIL>@ddd</EMAIL>
" +
" </ID>
" +
" ]]></RESPONSE>";
String xml = response.substring(response.indexOf("<ID>"), response.lastIndexOf("]]>"));
Id id = null;
try {
JAXBContext jc = JAXBContext.newInstance(Id.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource streamSource = new StreamSource(new StringReader(xml));
JAXBElement<Id> element = unmarshaller.unmarshal(streamSource, Id.class);
id = element.getValue();
} catch (JAXBException ex) {
ex.printStackTrace();
}
System.out.println(id.getEMAIL().size());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"email"
})
@XmlRootElement(name = "ID")
public static class Id {
@XmlElement(name = "EMAIL")
private List<String> email;
public List<String> getEMAIL() {
if (email == null) {
email = new ArrayList<>();
}
return this.email;
}
}
}
另一答案
您可以通过获取RESPONSE节点的内容来执行此操作,并以类似于您已经执行的方式继续操作。
例如,通过将其添加到您的代码中,
String content = list.item(0).getTextContent();
Document doc_ = docBuilder.parse(new InputSource(new StringReader(content)));
NodeList listId = doc_.getElementsByTagName("ID");
System.out.println("Total (list ID) : " + listId.getLength());
NodeList listEmail = doc_.getElementsByTagName("EMAIL");
System.out.println("Total (list EMAIL) : " + listEmail.getLength());
以上是关于解析响应xml并计算CDATA中的XML元素的主要内容,如果未能解决你的问题,请参考以下文章