是否可以使用Android中的DOM解析器解析特定的XML?

时间:2013-12-17 07:36:44

标签: android xml

以下格式是服务器的响应。我试图通过使用DOM解析这个问题,但得到的例外是“只允许一个根元素”。

<?xml version="1.0" encoding="UTF-8" ?>
  <responseCode>2000</responseCode>
  <responseText>Success</responseText>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>

2 个答案:

答案 0 :(得分:2)

这是无效的XML。答复应如下:

<root>
  <responseCode>2000</responseCode>
  <responseText>Success</responseText>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>
  <response>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
    <response1>on</response1>
  </response>
</root>

答案 1 :(得分:0)

使用XmlPullParser解析会更容易,而且效率也更高

实施例。 XML文件内容(作为code.xml保存在外部存储中)

<?xml version="1.0" encoding="utf-8"?>
<countries>
 <country>
   <name>Iran</name>
   <phonecode>+98</phonecode>
   <code>IRI</code>
 </country>
 <country>
   <name>United State</name>
   <phonecode>+1</phonecode>
   <code>USA</code>
 </country>
</countries>

让我们开始解析它

  1. 首先创建一个Helper类

    import android.util.Xml;
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class XmlDataParseHelper {
    
    private XmlPullParser parser;
    private static final String NULL = null;
    
    /**
     * 
     * @param in
     * @throws XmlPullParserException
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public XmlDataParseHelper(InputStream in) throws XmlPullParserException,
            IOException, IllegalArgumentException {
        try {
            parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, null);
            parser.nextTag();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * @return XmlPullParser
     */
    public XmlPullParser getParser() {
        return parser;
    }
    
    /**
     * 
     * @param parser
     * @param tag
     * @return String
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static String readTag(XmlPullParser parser, String tag)
            throws IOException, XmlPullParserException {
        String tagData = "";
        parser.require(XmlPullParser.START_TAG, NULL, tag);
        if (parser.next() == XmlPullParser.TEXT) {
            tagData = parser.getText();
            parser.nextTag();
        }
        parser.require(XmlPullParser.END_TAG, NULL, tag);
        return tagData;
    }
    
    /**
     * 
     * @param parser
     * @param tag
     * @param attributeName
     * @return String
     * @throws IOException
     * @throws XmlPullParserException
     */
    public static String readAttribute(XmlPullParser parser, String tag,
            String attributeName) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, NULL, tag);
        String attributeData = parser.getAttributeValue(NULL, attributeName);
        parser.nextTag();
        parser.require(XmlPullParser.END_TAG, NULL, tag);
        return attributeData;
    }
    
    }
    
  2. public InputStream readFile(String fileName) throws FileNotFoundException,
            IOException {
    //check external storage present
    // else throw new IOException();
    
    return new FileInputStream(Environment.getExternalStorageDirectory()
            + "/" + fileName);
    }
    
  3. 将InputStream传递给另一个初始化XMLPullParser对象的方法

     public void readXmlFile(String fileName) {
     try {
        if (fileName.isEmpty())
        throw new NullPointerException();
        readData(new XmlDataParseHelper(readFile(fileName)).getParser());
     } catch (IOException e) {
           e.printStackTrace();
     } catch (XmlPullParserException e) {
           e.printStackTrace();
     } catch (IllegalArgumentException e) {
           e.printStackTrace();
     }
     }
    
  4. Atlast将XMLPullParser object解析为

      public void readData(XmlPullParser parser)
                throws XmlPullParserException, IOException {
    int eventType = parser.getEventType();
    String tagName = "";
    Log.w("Developer", "Reading file...");
    while (eventType != XmlPullParser.END_DOCUMENT) {
        switch (eventType) {
            case XmlPullParser.START_DOCUMENT :
                Log.w("Developer", "Reading backup file...");
                break;
            case XmlPullParser.START_TAG :
                tagName = parser.getName();
                if (tagName.equals("countries")) {
                    Log.w("XMLParse", "Start TAG countries");
                    // do something when countries tag starts
                }
                if (tagName.equals("country")) {
                    Log.w("XMLParse", "Start TAG country");
                    // do some when country tag starts
                } else if (tagName.equals("name")) {
                    // read tag value using XmlDataParseHelper class
                    String countryName = XmlDataParseHelper.readTag(parser,
                                    "name");
                    Log.w("XmlParser", "Country name : "+countryName);
                } else if (tagName.equals("phonecode")) {
                    String countryPhoneCode = 
                                  XmlDataParseHelper.readTag(parser,"phonecode");
                    Log.w("XmlParser", "Country Phone code : "+countryPhoneCode);
                } else if (tagName.equals("code")) {
                    String countryCode = 
                                 XmlDataParseHelper.readTag(parser, "code");
                    Log.w("XmlParser", "Country code name : "+countryCode); 
                }
            break;
            case XmlPullParser.END_TAG :
                tagName = parser.getName();
                if (tagName.equals("countries")) {
                      // do something when counties tag is close.
                }           
            break;
        }
        eventType = parser.next();
    }
    Log.w("Developer", "File parsing complete...");
     }
    
  5. 要读取文件,只需使用存储在外部存储中的文件名称调用AsyncTask中的方法readXmlFile(String fileName)

  6. 整个android工作示例代码在这里https://gist.github.com/rachitrm/7810837或分叉项目http://www.github.com/rachitrm/rm-xmlparser/