我正在尝试创建一个测试来解析google distance matrix api的距离值。现在它全部在一个字符串中,所以我不必连接到api(发布了一个链接到xml读数。我在解析节点的值时遇到问题。我把所有内容都放在一个字符串中。
这是我运行时的测试我得到null而不是64275
public class GoogleDistanceMatrixXMLTest {
private static final String DISTANCE_XML_STRING = "<?xml version=\"1.0\"?><DistanceMatrixResponse><status>OK</status><origin_address>Muncie, IN, USA</origin_address><destination_address>Miami, FL, USA</destination_address><row><element><status>OK</status><duration><value>64275</value><text>17 hours 51 mins</text></duration><distance><value>1961951</value><text>1,219 mi</text></distance></element></row></DistanceMatrixResponse>";
private Document document;
@Before
public void setUp() throws ParserConfigurationException,
SAXException, IOException{
InputSource source = createInputSourceFromSampleXMLData();
document = parseXMLFrom(source);
}
private InputSource createInputSourceFromSampleXMLData() {
StringReader stringReader = new StringReader(DISTANCE_XML_STRING);
return new InputSource(stringReader);
}
private Document parseXMLFrom(InputSource source) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
return documentBuilder.parse(source);
}
@Test
public void testRetrieveDurationValue() throws ParserConfigurationException, SAXException, IOException {
String durationChildNodeValue = document.getFirstChild().getChildNodes().item(3).getFirstChild().getChildNodes().item(1).getFirstChild().getNodeValue();
Assert.assertEquals("64275", durationChildNodeValue);
}
答案 0 :(得分:0)
String durationChildNodeValue = document.getFirstChild()...;
应该是
String durationChildNodeValue = document.getDocumentElement()...;
无法保证文档元素是第一个孩子。处理指令可能是第一个孩子。