Java中的XML字符串解析

3

我正在尝试解析XML格式的字符串,例如:

<params  city="SANTA ANA" dateOfBirth="1970-01-01"/>

我的目标是将属性名称添加到一个数组列表中,例如{城市,出生日期},并将属性的值添加到另一个数组列表中,例如{Santa Ana,1970-01-01}。如果有建议,请帮忙!


4
你需要什么样的帮助? - PM 77-1
你需要使用SAX解析器。 - Andrew Tobilko
2个回答

1

使用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); 

1
  1. 创建 SAXParserFactory
  2. 创建 SAXParser
  3. 创建继承自 DefaultHandlerYourHandler
  4. 使用 SAXParserYourHandler 解析文件。

例如:

try {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(yourFile, new YourHandler());
} catch (ParserConfigurationException e) {
    System.err.println(e.getMessage());
}

在这里,yourFileFile 类的一个对象。

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;
    }
}`

SAX解析器和DefaultHandler的更多信息分别在这里这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接