У меня есть этот XML-файл:Извлечение элементов из CDATA
<description>
<![CDATA[
<tag1 hello world/><br/>
<b>Current Conditions:</b>
]]>
</description>
Мне нужно извлечь tag1
, br
и b
. Вот мой код:
NodeList nl = eElement.getElementsByTagName("description");
for (int j = 0; j < nl.getLength(); j++) {
Node n = nl.item(j);
Element e = (Element)n;
String s = getElement(e));
}
public static String getElement(Element e) {
NodeList list = e.getChildNodes();
String data;
for(int index = 0; index < list.getLength(); index++){
if(list.item(index) instanceof CharacterData){
CharacterData child = (CharacterData) list.item(index);
data = child.getData();
if(data != null && data.trim().length() > 0)
return child.getData();
}
}
return "";
}
Выход:
<tag1 hello world/><br/>
<b>Current Conditions:</b>
Но мне нужно иметь String [] str
со следующими значениями:
str[0] = "hello world";
str[1] = "";
str[3] = "Current Condition:";
Возможно, JAXB будет интересен вам. Он позволяет привязывать xml к стандартным классам Java. Таким образом, вам не придется выполнять какой-либо собственный анализ xml, и было бы намного быстрее адаптироваться к изменениям в схеме xml. – Simon