Java 如何解析XML数据
我有一个XML,就像Java 如何解析XML数据,java,xml,Java,Xml,我有一个XML,就像 <polygon> <coordinates> <coordinate order="1" long="75.9375" lat="32.91648534731439"/> <coordinate order="2" long="76.640625" lat="23.241346102386135"/> <coordinate order="3" long="88.59375" lat="31.0529339857051
<polygon>
<coordinates>
<coordinate order="1" long="75.9375" lat="32.91648534731439"/>
<coordinate order="2" long="76.640625" lat="23.241346102386135"/>
<coordinate order="3" long="88.59375" lat="31.052933985705163"/>
</coordinates>
</polygon>
我想得到每个坐标的long和lat值,并分配给string。
我试着说:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse( new InputSource(new StringReader(s)));
System.out.println(document.getChildNodes());
NodeList nl = document.getElementsByTagName("coordinates");
for (int i = 0; i < nl.getLength(); i++)
{
System.out.println("name is : "+nl.item(i).getNodeName());
System.out.println("name is : "+nl.item(i).getNodeValue());
}
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document Document=db.parse(新的InputSource(新的StringReader));
System.out.println(document.getChildNodes());
NodeList nl=document.getElementsByTagName(“坐标”);
对于(int i=0;i
字符串读取器是我传递的XML字符串,但我无法获取数据。您需要将每个
节点
强制转换为元素
,并且需要确保获得了正确的元素
for(int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
String lat = e.getAttribute("lat");
String longStr = e.getAttribute("long");
}
for(int i=0;i
根据您的层次结构创建节点列表如下所示。到达子节点后,开始使用元素迭代节点列表转换,并尝试使用elementObject.getAttribute(“标记名”)获取属性值。
XML结构:
多边形->坐标->坐标->属性-横向和纵向
NodeList valueList = doc.getElementsByTagName("polygon");
for (int i = 0; i < valueList.getLength(); ++i)
{
Element labTest = (Element) valueList .item(i);
String labTestType = labTest.getAttribute("type");
NodeList coordinates= labTest.getElementsByTagName("coordinates");
for (int j = 0; j < coordinates.getLength(); ++j)
{
Element value = (Element) coordinates.item(j);
String valueType = value.getAttribute("type");
NodeList coordinate= value.getElementsByTagName("coordinate");
for (int k = 0; k < coordinate.getLength(); ++k)
{
Element condition = (Element) coordinate.item(k);
String lat = e.getAttribute("lat");
String long = e.getAttribute("long");
}
}
}
NodeList valueList=doc.getElementsByTagName(“多边形”);
对于(int i=0;i
您试过调试代码吗?不特别是关于这个问题,但一般来说: