我需要解析这个我以字符串格式接收的xml我要提取lat和lon
<?xml version="1.0" encoding="UTF-8"?>
<rsp stat="ok">
<cell
lat="13.035037526666665"
lon="77.56784941333333"
mcc="404"
mnc="45"
lac="1020"
cellid="13443"
averageSignalStrength="0"
range="-1"
samples="15"
changeable="1"
radio="GSM" />
</rsp>
请有人帮我这个
我试过这个但没有得到输出
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(data));
Document doc = builder.parse(src);
String lat = doc.getElementsByTagName("lat").item(0).getTextContent();
String lon = doc.getElementsByTagName("lon").item(0).getTextContent();
答案 0 :(得分:0)
lat
是元素cell
的属性。因此,您不应使用getElementsByTagName("lat")
,而应使用getAttribute("lat")
:(代码未经测试)
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(data));
Document doc = builder.parse(src);
Element docElement = doc.getDocumentElement();
String lat = docElement.getElementsByTagName("cell").item(0).getAttribute("lat");
String lon = docElement.getElementsByTagName("cell").item(0).getAttribute("lon");
答案 1 :(得分:0)
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new FileInputStream("C:\\dev\\Workspace\\ahportal\\benefits-base-sdk\\portlets\\ah-hm-enrl-charts-portlet\\docroot\\WEB-INF\\src\\com\\aonhewitt\\portal\\base\\charts\\bean\\employee.xml"));
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
System.out.println("lat=> " + node.getAttributes().getNamedItem("lat")
.getNodeValue());
System.out.println("lon=> " + node.getAttributes().getNamedItem("lon")
.getNodeValue());
}
}
}
请尝试以上代码。它应该工作。如果它不适合你,请告诉我。
答案 2 :(得分:0)
根据您对坐标的处理方式,我建议将它们包装到一个位置对象中,并按住lat和amp; LON。
我不建议使用DOM API,而是使用像JAXB这样的数据绑定库,或者使用更短,更灵活的方法data projection library(披露:我是该项目的附属机构)并将值自动转换为Double
。
import org.xmlbeam.XBProjector;
import org.xmlbeam.annotation.XBRead;
public class ReadCoords {
// Object holding coordinates
public interface Location {
// Access methods for coordinates
@XBRead("./@lat")
Double getLat();
@XBRead("./@lon")
Double getLon();
}
public static void main(String[] args) {
Location location = new XBProjector().io().url("res://data.xml").evalXPath("/rsp/cell").as(Location.class);
System.out.println(location.getLat()+"/"+location.getLon());
}
}