Can you help me adjust this code so it manages to parse the XML? If I drop the XML namespace it works:
你能帮助我调整这段代码,以便它能够解析XML吗?如果我删除XML命名空间,它可以工作:
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 个解决方案
#1
9
-
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.
您必须在XPath中使用前缀,例如: g。:“/ my:foo / my:bar”您可以选择任何您喜欢的前缀 - 它与您在XML文件中使用或不使用的前缀没有任何关系 - 但您必须选择一个。这是XPath 1.0的限制。
-
You must perform prefix mapping from "my" to "http://foo.bar/boo" (not to "http://www.w3.org/2001/XMLSchema-instance")
您必须执行从“my”到“http://foo.bar/boo”的前缀映射(而不是“http://www.w3.org/2001/XMLSchema-instance”)
#1
9
-
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.
您必须在XPath中使用前缀,例如: g。:“/ my:foo / my:bar”您可以选择任何您喜欢的前缀 - 它与您在XML文件中使用或不使用的前缀没有任何关系 - 但您必须选择一个。这是XPath 1.0的限制。
-
You must perform prefix mapping from "my" to "http://foo.bar/boo" (not to "http://www.w3.org/2001/XMLSchema-instance")
您必须执行从“my”到“http://foo.bar/boo”的前缀映射(而不是“http://www.w3.org/2001/XMLSchema-instance”)