我正在尝试解析XML格式的字符串,例如:
<params city="SANTA ANA" dateOfBirth="1970-01-01"/>
我的目标是将属性名称添加到一个数组列表中,例如{城市,出生日期},并将属性的值添加到另一个数组列表中,例如{Santa Ana,1970-01-01}。如果有建议,请帮忙!
使用JDOM(http://www.jdom.org/docs/apidocs/):
String myString = "<params city='SANTA ANA' dateOfBirth='1970-01-01'/>";
SAXBuilder builder = new SAXBuilder();
Document myStringAsXML = builder.build(new StringReader(myString));
Element rootElement = myStringAsXML.getRootElement();
ArrayList<String> attributeNames = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.addAll(rootElement.getAttributes());
Iterator<Element> childIterator = rootElement.getDescendants();
while (childIterator.hasNext()) {
Element childElement = childIterator.next();
attributes.addAll(childElement.getAttributes());
}
for (Attribute attribute: attributes) {
attributeNames.add(attribute.getName());
values.add(attribute.getValue());
}
System.out.println("Attribute names: " + attributeNames);
System.out.println("Values: " + values);
SAXParserFactory
。SAXParser
。DefaultHandler
的 YourHandler
。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;
}
}`