使用XPath&解析XMLJava中的名称空间 [英] Parse XML with XPath & namespaces in Java

查看:41
本文介绍了使用XPath&解析XMLJava中的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我调整此代码,使其成功解析XML吗?如果删除XML名称空间,它将起作用:

Can you help me adjust this code so it manages to parse the XML? If I drop the XML namespace it works:

String webXmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                       "<foo xmlns=\"http://foo.bar/boo\"><bar>baz</bar></foo>";
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(new StringInputStream(webXmlContent));

NamespaceContextImpl namespaceContext = new NamespaceContextImpl();
namespaceContext.startPrefixMapping("foo", "http://www.w3.org/2001/XMLSchema-instance");
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(namespaceContext);

XPathExpression expr = xpath.compile("/foo/bar");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Got " + nodes.getLength() + " nodes");

推荐答案

  1. 您必须在XPath中使用前缀,例如.g .:"/my:foo/my:bar"您可以选择任何喜欢的前缀-它与您在XML文件中使用或不使用的前缀没有任何关系-但您必须选择一个.这是XPath 1.0的局限性.

  1. You must use a prefix in your XPath, e. g.: "/my:foo/my:bar" You can choose any prefix you like - it doesn't have anything to do with the prefixes you use or don't use in the XML file - but you must choose one. This is a limitation of XPath 1.0.

您必须执行从我"到" http://foo.bar/boo"(而不是" http://www.w3.org/2001/XMLSchema-instance)

You must perform prefix mapping from "my" to "http://foo.bar/boo" (not to "http://www.w3.org/2001/XMLSchema-instance")

这篇关于使用XPath&amp;解析XMLJava中的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆