我有一个很大的xml:
<SomeRequest>
<Reservation>
...
</Reservation>
<Payment>
<cardNumber>....</cardNumber>
</Payment>
</SomeRequest>
现在我想从这个xml获得cardNumber
值。它是String,我无法将其解析为xml Document
因为它需要太多时间。
所以,我有这个string
,我就这样使用XPath
:
String field = "/SomeRequest/Payment/cardNumber/text()";
XPathExpression compile = XPATH_FACTORY.newXPath().compile(field);
String value = compile.evaluate(new InputSource(new StringReader(request))); //request is xml string
但在执行此操作后,value
为空。我尝试在xml Document
(解析它)上执行它然后它工作。但现在我想用简单的String
来做。
我不想在这个字符串上使用正则表达式,因为它可以提供很多问题。
如何使用XPath获取此cardNumber
值?
答案 0 :(得分:1)
你是正确的,有效的
public class XpathTest {
private XPathFactory XPATH_FACTORY = new XPathFactoryImpl();
private String request = "<SomeRequest>\n" +
"<Reservation>\n" +
"...\n" +
"</Reservation>\n" +
"<Payment>\n" +
"<cardNumber>123</cardNumber>\n" +
"</Payment>\n" +
"</SomeRequest>";
@Test
public void name() throws Exception {
String field = "/SomeRequest/Payment/cardNumber/text()";
XPathExpression compile = XPATH_FACTORY.newXPath().compile(field);
String value = compile.evaluate(new InputSource(new StringReader(request)));
assertThat(value, equalTo("123"));
}
}
答案 1 :(得分:-1)
您可以在toString
上使用Document
。