带有XMLUnit 2和默认命名空间的Java XPath

时间:2016-03-15 21:12:33

标签: java xml xpath xml-namespaces xmlunit-2

我在使用XMLUnit 2.0.0和默认命名空间编写XPath时遇到了问题。这是我的示例xml:

import random, 
start = raw_input('Welcome to the mining game! Type "Start" to continue. ')
if str.upper(start) == ("START"):
  default_cash = 14
  print "You have %g cash." % default_cash
  choices = raw_input("What would you like to do? Type 'Mine' to dig for ores, or type 'Shop' to go shopping for equipment. ")
  if str.upper(choices) == ("MINE"):
    ores = ["emerald", "ruby", "silver", "gold", "diamods", "nothing"]
    ores_random = random.choice(ores)
    print "you found %s!" % ores_random`

我无法使用以下XMLUnit XPath代码访问任何元素:

<a xmlns="uri:foo">
    <b>value</b>
</a>

如何使用默认命名空间使用XPathEngine / XPath访问元素?

1 个答案:

答案 0 :(得分:1)

我找到的答案是在XPath中使用单个&#39;前缀:&#39 ;.

"/:a/:b"

这解决了我的问题。总之,我做了以下几点:

XPathEngine engine = new JAXPXPathEngine();
engine.setNamespaceContext(new HashMap<String, String>(1) {{
    put(DEFAULT_NS_PREFIX, "uri:foo");
}});
assertEquals("value", engine.evaluate("/:a/:b",
             Input.fromString("<a xmlns=\"uri:foo\"><b>value</b></a>").build()));