【发布时间】:2013-05-17 12:21:59
【问题描述】:
我有这个 XML 文件:
<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 架构中的变化会更快。