例如,我试图通过XML格式的String进行解析。
<params city="SANTA ANA" dateOfBirth="1970-01-01"/>
我的目标是在{city,dateOfBirth}等数组列表中添加属性名称,并在{Santa Ana,1970-01-01}等另一数组列表中添加属性值,请提供任何建议!
SAXParserFactory
。SAXParser
。YourHandler
,扩展DefaultHandler
。SAXParser
和解析文件YourHandler
。例如:
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(yourFile, new YourHandler());
} catch (ParserConfigurationException e) {
System.err.println(e.getMessage());
}
其中yourFile
-File
类的对象。
在YourHandler
课堂上:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class YourHandler extends DefaultHandler {
String tag = "params"; // needed tag
String city = "city"; // name of the attribute
String value; // your value of the city
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(localName.equals(tag)) {
value = attributes.getValue(city);
}
}
public String getValue() {
return value;
}
}`
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句