java 从XML中取出某个节点的值

publicStringgetCode(StringCode)throwsHTException{LocalInfoActionMZactionMZ=newLocalIn... public String getCode(String Code) throws HTException
{
LocalInfoActionMZ actionMZ = new LocalInfoActionMZ();
String str = actionMZ.getCode(Code);
return null;

actionMZ类下面的getCode方法
public String getCode(String Code)throws HTException
{
LocalInfoFunctionMZ function = new LocalInfoFunctionMZ();
String retStr=null;.................(省略)........................
System.out.println("得到的XML消息体"+retStr);

这个retStr就是一个XML消息体,格式是
<message msgType="response" msgId="String" timestampCreated="2010-5-13 15:55:54" version="String">
<response>
<code>0</code>
<description>成功</description>
</response>
<body bodyId="1">
<id>11223344</id>
</body>
</message>

我想取出这个id的值,返回到public String getCode(String Code) 这个方法里面。
id值是null就返回空,如果有值,就返回这个值。

这个值应该怎么取,谢谢
展开
 我来答
完三青若阳兔嗨1C
推荐于2017-12-15 · TA获得超过185个赞
知道答主
回答量:66
采纳率:66%
帮助的人:37.8万
展开全部
代码如下:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class FileTest {

/**
* @param args
*/
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("d:/test.xml");
//得到根节点
Element root = doc.getDocumentElement();
NodeList nl = root.getElementsByTagName("id");
Element e = (Element) nl.item(0);
String id=e.getTextContent();
System.out.println("id的值为:"+id);
}catch(Exception e){
e.printStackTrace();
}
}

}
上面的代码中我把
<message msgType="response" msgId="String" timestampCreated="2010-5-13 15:55:54" version="String">
<response>
<code>0</code>
<description>成功</description>
</response>
<body bodyId="1">
<id>11223344</id>
</body>
</message>
这段内容放到了D盘下的test.xml文件中
你如果要用可以直接将得到的给字符串加载成Document对象,就可以取到了。
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式