我正在使用XmlPullParser从XML文档中提取数据。我的XML文档的结构如下:

<creature id="1">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>
<creature id="2">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>
<creature id="3">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>


如果我的XML文件中只有一个生物,那么我的代码当前正在工作。

我正在寻找一种根据生物ID选择生物的方法。例如,如果ID为2,则XMLPullParser将仅解析生物ID =“ 2”下的XML。

到目前为止,这是我的代码:

xpp.next();
String elName = "";
int encounterId = 0;
int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT)
    {

 if(eventType == XmlPullParser.START_DOCUMENT)
 {
     System.out.println("START_DOCUMENT "+xpp.getName());
 }
 else if(eventType == XmlPullParser.START_TAG)
 {
     if(encounterId >= 0) {
         if(xpp.getName().equalsIgnoreCase("creature")) {
             System.out.println("inside while loop --- "+xpp.getName());
             try {
                 encounterId = Integer.parseInt(xpp.getAttributeValue(0));
                 System.out.println("attribute value = " + encounterId);
             } catch (NumberFormatException e) {
                 Log.e("attribute value error", e.getMessage());
             }
             //DETERMINE ELEMENT NAME
         } else if(xpp.getName().equalsIgnoreCase("name")) {
             System.out.println("inside while loop --- "+xpp.getName());
             elName = "name";
         } else if(xpp.getName().equalsIgnoreCase("type")) {
             elName = xpp.getName();
             elName = "type";
         } else if(xpp.getName().equalsIgnoreCase("size")) {
             elName = xpp.getName();
         elname = "size";
             }

 } else if(eventType == XmlPullParser.END_TAG) {
     System.out.println("End tag "+xpp.getName());

 } else if(eventType == XmlPullParser.TEXT) {
     //COLLECT DATA

     if(elName.equalsIgnoreCase("name")) {
        this.name = xpp.getText();
     } else if(elName.equalsIgnoreCase("type"))  {
        this.race = xpp.getText();
     } else if(elName.equalsIgnoreCase("size")) {
        this.gender = xpp.getText();
 }
eventType = xpp.next();
}


谢谢!

最佳答案

您应该为此使用XPath

    XmlPullParser xpp = context.getResources().getXml(R.xml.zoo_table);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        String askFor2 = "//creature[@ID='2']";
        NodeList creaturesNodes = (NodeList) xpath.evaluate(askFor2, xpp, XPathConstants.NODESET);

        // here you have all such creatures - the list of one node in your case

关于java - 使用XMLpullParser浏览XML文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9196262/

10-10 03:39