栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Java XPath解析XML简单字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java XPath解析XML简单字符串

您不能将其重复

InputSource
用于多个
evaluate()
调用,因为它会自动关闭。因此,您将获得
Streamclosed
IO异常。试试这个

InputSource source1 = new InputSource(new StringReader(xml));InputSource source2 = new InputSource(new StringReader(xml));String msg = xpath.evaluate("/resp/msg", source);String status = xpath.evaluate("/resp/status", source2);System.out.println("msg=" + msg + ";" + "status=" + status);

编辑:
更好的方法是使用A

documentBuilderFactory
解析您的XML并构建
document
第一个(使用JAXP的DOM
API),然后可以在多个XPath评估中重复使用。

String xml = "<resp><status>good</status><msg>hi</msg></resp>";InputSource source = new InputSource(new StringReader(xml));documentBuilderFactory dbf = documentBuilderFactory.newInstance();documentBuilder db = dbf.newdocumentBuilder();document document = db.parse(source);XPathFactory xpathFactory = XPathFactory.newInstance();XPath xpath = xpathFactory.newXPath();String msg = xpath.evaluate("/resp/msg", document);String status = xpath.evaluate("/resp/status", document);System.out.println("msg=" + msg + ";" + "status=" + status);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号