通过Android中的id将XML链接到java代码

时间:2017-05-11 20:35:44

标签: java android xml

我们如何通过id将XML链接到java代码? 例如,当我们点击按钮时,我们会更改图层或从textView中提供String。

1 个答案:

答案 0 :(得分:0)

我建议使用DOM或SAX解析器。 DOM教程找到了here关于如何读取XML并解析各个元素的信息。找到了SAX的教程here

以下是一个SAX解析器示例: 包ca.ubc.cs.recommender.bugzilla.parser;

import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;

/**
 *     parse the XML information
 *     
 * @author whitecat
 *
 */
public class XMLParser extends DefaultHandler {

    // Remember information being parsed
    private StringBuffer accumulator;
    private StringBuffer xmlFile;

    public XMLParser(StringBuffer xmlFile) {
        this.xmlFile = xmlFile;
    }

    /**
     * Called at the start of the document (as the name suggests)
     */
    public void startDocument() {
        // Use accumulator to remember information parsed. Just initialize for
        // now.
        accumulator = new StringBuffer();
    }

    /**
     * Called when the parsing of an element starts. (e.g., <book>)
     * 
     * Lookup documentation to learn meanings of parameters.
     */
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
        accumulator.setLength(0);
    }

    /**
     * Called for values of elements
     * 
     * Lookup documentation to learn meanings of parameters.
     */
    public void characters(char[] temp, int start, int length) {
        // Remember the value parsed
        accumulator.append(temp, start, length);
    }

    /**
     * Called when the end of an element is seen. (e.g., </title>)
     * 
     * Lookup documentation to learn meanings of parameters.
     * 
     * @throws SAXException
     */
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.toLowerCase().equals("id") || qName.toLowerCase().equals("thetext") ) {
            xmlFile.append(accumulator.toString().trim().toLowerCase());
        }

        // Reset the accumulator because we have seen the value
        accumulator.setLength(0);
    }
}

这里我设置了一个累加器,它在访问XML标签时收集字符串。然后,当我到达结束标记时,我设置了ID。我不确定您的XML是如何设置的,但这是解析XML并在JAVA中使用它的一种方法。