我想解析这种 XML 字符串:
<Objects>
<Object type="crs" obj_id="192">
<Title>Course 1</Title>
<Description>this is description</Description>
<CreateDate>2012-10-16 12:53:12</CreateDate>
<LastUpdate>2012-10-16 12:53:54</LastUpdate>
</Object>
<Object type="frm" obj_id="202">
<Title>Forum 1</Title>
<Description>this is description</Description>
<CreateDate>2012-10-30 01:06:41</CreateDate>
<LastUpdate>2012-10-30 01:06:41</LastUpdate>
</Object>
</Objects>
我已经解析了具有相同结构的 XML 字符串,但只是使用了标签 <Object>。现在我想获取标签对象中的信息以获取类型=“xxx”的字符串。
这就是我进行此类解析的方式:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource xml = new InputSource();
xml.setCharacterStream(xmlSTring);
Document doc = db.parse(xml);
NodeList nodes = doc.getElementsByTagName("Object");
// iterate objects
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// get first attribute
NodeList ref_id = element.getElementsByTagName("title");
Element line = (Element) ref_id.item(0);
System.out.println("title: " + getCharacterDataFromElement(line));
}
}
catch (Exception e) {
e.printStackTrace();
}
private static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
提前致谢。