java 解析服务器返回的XML格式数据
要解析的数据是:<data><UId>123</UId><username>jack</username><nickname>hehe</nickname></data>...
要解析的数据是:
<data>
<UId>123</UId>
<username>jack</username>
<nickname>hehe</nickname>
</data>
我现在的情况是能拿到这个字符串或者是输入流的格式。documentbuilder对象也拿到,最关键的是解析过程,解析过程我怎么写也写不对。求高手帮忙写下吧、满意了追加50分。。 展开
<data>
<UId>123</UId>
<username>jack</username>
<nickname>hehe</nickname>
</data>
我现在的情况是能拿到这个字符串或者是输入流的格式。documentbuilder对象也拿到,最关键的是解析过程,解析过程我怎么写也写不对。求高手帮忙写下吧、满意了追加50分。。 展开
3个回答
展开全部
public void parseXML(String filename) {
System.out.println("parse-start");
try {
System.out.println("try-catch-start");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(filename);
NodeList employees = document.getChildNodes();
System.out.println("nodlist-over");
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
for (int k = 0; k < employeeMeta.getLength(); k++) {
System.out.println(employeeMeta.item(k).getNodeName()
+ ":" + employeeMeta.item(k).getTextContent());
}
}
}
System.out.println("解析完毕");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
System.out.println("parse-start");
try {
System.out.println("try-catch-start");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(filename);
NodeList employees = document.getChildNodes();
System.out.println("nodlist-over");
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
for (int k = 0; k < employeeMeta.getLength(); k++) {
System.out.println(employeeMeta.item(k).getNodeName()
+ ":" + employeeMeta.item(k).getTextContent());
}
}
}
System.out.println("解析完毕");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
sax或者dom4j,sax更好用,读取速度快
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
建议去百度一下dom4j
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询