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

Java中具有名称空间的XPath

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

Java中具有名称空间的XPath

  1. 简短的答案:使用XPath
    local-name()
    。这样:
    xPathFactory.newXPath().compile("//*[local-name()='requestURL']/text()");
    将返回
    /CAMERA/Streaming/status
  2. 或者,您可以实现一个
    NamespaceContext
    映射名称空间名称和URI的,并在查询之前在XPath对象上对其进行设置。
  3. 看一下这篇博客文章, 更新: 该文章已结束,您可以在webarchive上看到它

解决方案1样本:

XPath xpath = XPathFactory.newInstance().newXPath();String responseStatus = xpath.evaluate("//*[local-name()='ResponseStatus']/text()", document);System.out.println("-> " + responseStatus);

解决方案2样本:

// load the documentdocument document = ...;NamespaceContext ctx = new NamespaceContext() {    public String getNamespaceURI(String prefix) {        return prefix.equals("urn") ? "urn:camera-org" : null;     }    public Iterator getPrefixes(String val) {        return null;    }    public String getPrefix(String uri) {        return null;    }};XPath xpath = XPathFactory.newInstance().newXPath();xpath.setNamespaceContext(ctx);String responseStatus = xpath.evaluate("//urn:ResponseStatus/text()", document);System.out.println("-> " + responseStatus);

编辑

这是一个完整的示例,它可以正确检索元素:

String xml = "<urn:ResponseStatus version="1.0" xmlns:urn="urn:camera-org">rn" + //        "rn" + //        "<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>rn" + //        "<urn:statusCode>4</urn:statusCode>rn" + //        "<urn:statusString>Invalid Operation</urn:statusString>rn" + //        "<urn:id>0</urn:id>rn" + //        "rn" + //        "</urn:ResponseStatus>";documentBuilderFactory factory = documentBuilderFactory.newInstance();factory.setNamespaceAware(true);documentBuilder builder = factory.newdocumentBuilder();document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));XPath xpath = XPathFactory.newInstance().newXPath();xpath.setNamespaceContext(new NamespaceContext() {    public String getNamespaceURI(String prefix) {        return prefix.equals("urn") ? "urn:camera-org" : null;    }    public Iterator<?> getPrefixes(String val) {        return null;    }    public String getPrefix(String uri) {        return null;    }});XPathexpression expr = xpath.compile("//urn:ResponseStatus");Object result = expr.evaluate(doc, XPathConstants.NODESET);NodeList nodes = (NodeList) result;for (int i = 0; i < nodes.getLength(); i++) {    Node currentItem = nodes.item(i);    System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");}


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

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

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