这是我的第一篇文章,所以如果我没有说清楚,我会很乐意提供更多细节。 我正在使用 Java 编写路由 API。文件的大部分都正确解析了一部分。我感兴趣的 XML 部分如下所示:
<way id="30184957" user="Central America" uid="69853" visible="true" version="2" changeset="4961491" timestamp="2010-06-11T10:52:19Z">
<nd ref="332597303"/>
<nd ref="332597551"/>
<nd ref="332597552"/>
<tag k="highway" v="residential"/>
<tag k="name" v="Rae's Court"/>
</way>
</b>
我的代码的相关部分如下所示:
public void startElement(String uri, String localName, String qName, Attributes attributes)
{
if (qName == "node") //if the tag value is node
{
Node currentNode = new Node(0, 0, 0); //new node with all 0 values
currentNode.nodeID = Integer.parseInt(attributes.getValue(0)); //set the ID to the id of the node
currentNode.nodeLat = Double.parseDouble(attributes.getValue(1)); //set the Lat to the Lat of the node
currentNode.nodeLong = Double.parseDouble(attributes.getValue(2)); //set the Long to the Long of the node
allNodes.add(currentNode);
}
if (qName == "way") //if tag value is way
{
currentWay = new Way(0, null); //create a new way with 0 values
currentWay.wayID = Integer.parseInt(attributes.getValue(0)); //set the way id to the id of the way
//
}
if (qName == "nd") //if tag value is nd
{
Node searchNode = getNodeByID(Integer.parseInt(attributes.getValue(0))); //use getNodeByID method to check if
currentWay.containedNodes.add(searchNode);
}
}
我的问题:
我正在尝试创建一个包含 ID 和它包含的节点列表(nd 标记)的方法对象,nd 标记只是对先前成功创建的节点对象的引用。目前我正在使用 2 个 ArrayLists,一个用于节点,另一个用于方法。但是,getNodeByID()
方法每次遇到 nd 时都必须在列表中进行搜索,这大大降低了我处理较大 XML 文件的速度。
我似乎无法找到一种方法来读取 nd,而是必须在不同的 if 语句中搜索它们。
有什么方法可以找到一种方法,然后在同一条语句中,所有 nd 都与之相关吗?如果是这样的话,当我计划将这些数组列表更改为 HashMap 时,创建我的对象会容易得多。
抱歉,如果我没说清楚...我不太擅长用文字描述这些问题。
最佳答案
而不是将要搜索的节点存储在 List
中, 使用 Map<Integer,Node>
.这样搜索将是 O(1) 而不是 O(n)。如果您需要按输入顺序排列它们,请将它们添加到 List
也供以后使用,但使用 Map
用于搜索。
代替
allNodes.add(currentNode);
你会
allNodes.put(currentNode.nodeId, currentNode);
关于java - 如何使用 SAX 解析器读取其他标记中包含的 XML 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204897/