本文介绍了使用Java读取XML单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试读取一个看起来像这样的XML行:
I'm trying to read a single XML line that looks like this:
<position lat="59.3252414125" long="18.0750236375" accuracy="1000"></position>
这里的目标是将"lat","long"和"accuracy"的值放入三个Java变量中.
The goal here is take the values of "lat", "long" and "accuracy" and put them in three Java variables.
我想我应该提到该行是从XML读取的,因此它看起来并不容易编辑.
I guess I should've mentioned that the line is read from an XML, so it's not easily editable as it would appear.
推荐答案
尝试:
String s = "<position lat=\"59.3252414125\" long=\"18.0750236375\" accuracy=\"1000\"></position>";
InputSource is = new InputSource(new StringReader(s));
DOMParser dp = new DOMParser();
dp.parse(is);
Document doc = dp.getDocument();
NodeList nl = doc.getElementsByTagName("position");
Node n = nl.item(0);
NamedNodeMap nnm = n.getAttributes();
String lat = nnm.getNamedItem("lat").getFirstChild().getTextContent();
String longg = nnm.getNamedItem("long").getFirstChild().getTextContent();
String accuracy = nnm.getNamedItem("accuracy").getFirstChild().getTextContent();
建议的读物:
- http://www.cafeconleche.org/books/xmljava/chapters/ch05.html
- http://download.oracle.com/javase/tutorial/jaxp/index.html
- 查看 XOM 太简单又好了.
- http://www.cafeconleche.org/books/xmljava/chapters/ch05.html
- http://download.oracle.com/javase/tutorial/jaxp/index.html
- Look into XOM it's too simple and good.
这篇关于使用Java读取XML单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!