【发布时间】:2017-10-11 00:38:00
【问题描述】:
我们如何通过 id 将 XML 链接到 java 代码? 例如,当我们单击按钮时,我们会更改图层或从 textView 提供字符串。
【问题讨论】:
-
这个问题需要详细说明。将 XML 链接到 Java 的一种简单方法是使用 saxparser。
我们如何通过 id 将 XML 链接到 java 代码? 例如,当我们单击按钮时,我们会更改图层或从 textView 提供字符串。
【问题讨论】:
我建议使用 DOM 或 SAX 解析器。 DOM 教程找到了here,介绍了如何读取 XML 并解析各个元素。并找到了 SAX 的教程here。
这是一个 SAX 解析器示例: 包 ca.ubc.cs.recommender.bugzilla.parser;
导入 org.xml.sax.Attributes; 导入 org.xml.sax.SAXException; 导入 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 中使用它的一种方法。
【讨论】: