我想分析這種XML字符串:如何在標籤內解析帶有數據的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中的信息以獲取type =「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 "?";
}
在此先感謝。
你有DTD嗎? – durron597
我是一個新手,我不確定什麼是DTD,但是如果有幫助,我可以從soap請求中獲得XML字符串,我不會編輯它。 我的意思是,我只是得到這個代碼,沒有更多。 – Davis
哦,是的...搜索我有一個.dtd文件。 – Davis