Java 在android中使用SAXParser访问XML中的子节点
我的XML树具有以下结构:Java 在android中使用SAXParser访问XML中的子节点,java,android,xml,saxparser,Java,Android,Xml,Saxparser,我的XML树具有以下结构: <building id="5" name="Barracks" hp="2000" > <cost metal="100" wood = "300"></cost> <unit id="1" name="Swordsman" hp="40" attack="3"/> <tech id="1" name="Research Heavy Swordsman"/> </buildin
<building id="5" name="Barracks" hp="2000" >
<cost metal="100" wood = "300"></cost>
<unit id="1" name="Swordsman" hp="40" attack="3"/>
<tech id="1" name="Research Heavy Swordsman"/>
</building>
这是我用来访问它的代码:
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
int civId=0, id=0;
if(qName.equalsIgnoreCase("building"))
{
inBuilding = true;
building = true;
//Fetching the ID of TownCenter, we use it as a reference to fetch the child nodes.
id = Integer.parseInt(attributes.getValue("id"));
if(id==5)
{
XMLfetch.put("id", attributes.getValue("id"));
XMLfetch.put("name", attributes.getValue("name"));
XMLfetch.put("hp", attributes.getValue("hp"));
......
}
}
if(inBuilding && id==5){ //<----- Condition which matters
if(qName.equalsIgnoreCase("cost")){
Log.i("resources", "Wood "+attributes.getValue("wood"));
Log.i("resources", "MetaL "+attributes.getValue("metal"));
XMLfetch.put("costWood", attributes.getValue("wood"));
XMLfetch.put("costMetal", attributes.getValue("stone"));
}
}
}
// END ELEMENT here
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(inBuilding)
{
if(qName.equalsIgnoreCase("building")) {
building=false;
//inBuilding=false;
}
if(qName.equalsIgnoreCase("cost")){
inBuilding=false;
}
}
}
public void startElement(字符串uri、字符串localName、字符串qName、,
属性)引发SAX异常{
int civId=0,id=0;
if(qName.equalsIgnoreCase(“建筑”))
{
内置=真;
建筑=真实;
//获取TownCenter的ID时,我们将其用作获取子节点的引用。
id=Integer.parseInt(attributes.getValue(“id”));
如果(id==5)
{
XMLfetch.put(“id”,attributes.getValue(“id”);
XMLfetch.put(“名称”,attributes.getValue(“名称”);
XMLfetch.put(“hp”,attributes.getValue(“hp”);
......
}
}
如果(inBuilding&&id==5){/问题解决了!我在错误的位置声明了inBuilding变量。:(……因此,变量被重写了,我无法检测到我在哪里。感谢所有阅读并试图给出解决方案的人。:)civId和id变量在startElement()中声明,这意味着它们每次都会被重新写入…因此它们是无用的。它们需要在不被重新写入的任何地方声明。感谢ianhanniballake您发布的XML文件缺少一个名为=Barracks的引号。您能发布什么属性。getValue(“id”)以及if(id==5)前面的id是什么吗调用?问题解决了!我在错误的位置声明了内置变量。:(……因此,变量被重写了,我无法检测到我在哪里。感谢所有阅读它并试图给出解决方案的人。:)civId和id变量在startElement()中声明,这意味着它们每次都会被重写…因此它们是无用的。它们需要在任何不会被重写的地方被声明。谢谢ianhanniballake