我有一个代码,用于解析响应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>
谢谢
答案 0 :(得分:0)
您可以通过获取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());
答案 1 :(得分:0)
RESPONSE标记之间的所有内容都将被视为字符串。试试:
public class Main {
public static void main(String... args) {
String response = "<RESPONSE><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ID>\n" +
" <EMAIL>xxx@yyy</EMAIL>\n" +
" <EMAIL>klihf@kjf</EMAIL>\n" +
" <EMAIL>ddd@fff</EMAIL>\n" +
" <EMAIL>@ddd</EMAIL>\n" +
" </ID>\n" +
" ]]></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;
}
}
}