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

操纵/编辑现有xml文档的最佳Java Xml解析器

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

操纵/编辑现有xml文档的最佳Java Xml解析器

使用JDOM,获取InputStream并将其设为document:

InputStream inputStream = (InputStream)httpURLConnection.getContent();documentBuilderFactory docbf = documentBuilderFactory.newInstance();docbf.setNamespaceAware(true);documentBuilder docbuilder = docbf.newdocumentBuilder();document document = docbuilder.parse(inputStream, baseUrl);

那时,您在Java对象中具有XML。做完了 简单。

您既可以使用文档对象和Java API来遍历它,也可以使用XPath,我发现它很容易(一旦我了解了它)。

构建一个XPath对象,这需要一点时间:

public static XPath buildXPath() {    XPathFactory factory = XPathFactory.newInstance();    XPath xpath = factory.newXPath();    xpath.setNamespaceContext(new AtomNamespaceContext());    return xpath;}public class AtomNamespaceContext implements NamespaceContext {    public String getNamespaceURI(String prefix) {        if (prefix == null) throw new NullPointerException("Null prefix");        else if ("a".equals(prefix)) return "http://www.w3.org/2005/Atom";        else if ("app".equals(prefix)) return "http://www.w3.org/2007/app";        else if ("os".equals(prefix)) return "http://a9.com/-/spec/opensearch/1.1/";        else if ("x".equals(prefix))  return "http://www.w3.org/1999/xhtml";        else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;        return XMLConstants.NULL_NS_URI;    }    // This method isn't necessary for XPath processing.    public String getPrefix(String uri) {        throw new UnsupportedOperationException();    }    // This method isn't necessary for XPath processing either.    public Iterator getPrefixes(String uri) {        throw new UnsupportedOperationException();    }}

然后只需使用它(幸运的是)根本不需要太多时间:

return Integer.parseInt(xpath.evaluate("/a:feed/os:totalResults/text()", document));


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

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

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