gpt4 book ai didi

java - 在 Java 中解析 XML,其中数据位于属性旁边

转载 作者:行者123 更新时间:2023-12-01 17:16:55 25 4
gpt4 key购买 nike

我需要在Java中获取某些XML对象的值,但它们在属性标签中。我不知道该怎么做。

XML 示例:

<node id="359832" version="5" timestamp="2008-05-20T15:20:46Z" uid="4499" changeset="486842" lat="50.9051565" lon="6.963755">
<tag k="amenity" v="restaurant"/>
<tag k="name" v="Campus"/>
</node>
<node id="451153" version="4" timestamp="2009-09-17T18:09:14Z" uid="508" changeset="2514480" lat="51.6020306" lon="-0.1935029">
<tag k="amenity" v="restaurant"/>
<tag k="created_by" v="JOSM"/>
<tag k="name" v="Sun and Sea"/>
</node>

我需要获取lat的值和lon ,位于 <node> 内除了 <tag k="name" v="Sun and Sea"/> 的值,并用每组做一些事情。

伪代码:

foreach(node in xmlFile)
{
String name = this.name;
double lat = this.lat;
double lon = this.lon;
//my own thing here
}

我已经看过,但找不到任何有关如何获取 lat 值的信息和lon ,因为它们位于属性旁边而不是嵌套。我不需要使用输入流,xml 文件太小,无法将其存储在内存中。

最佳答案

package com.sandbox;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class Sandbox {

public static void main(String argv[]) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(Sandbox.class.getResourceAsStream("/foo.xml"));

NodeList nodeNodeList = document.getElementsByTagName("node");

for (int i = 0; i < nodeNodeList.getLength(); i++) {

Node nNode = nodeNodeList.item(i);

System.out.println(nNode.getAttributes().getNamedItem("lat").getNodeValue());
System.out.println(nNode.getAttributes().getNamedItem("lon").getNodeValue());

}

}


}

打印出来的:

50.9051565
6.963755
51.6020306
-0.1935029

关于java - 在 Java 中解析 XML,其中数据位于属性旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21394968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com