解析响应xml并计算CDATA中的XML元素

问题描述 投票:0回答:2

我有一个代码,我解析响应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>

谢谢

java xml post xml-parsing response
2个回答
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;
    }
}

}


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());
© www.soinside.com 2019 - 2024. All rights reserved.