【问题标题】:XML string parsing in JavaJava中的XML字符串解析
【发布时间】:2015-06-25 23:35:04
【问题描述】:

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

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

我的目标是在数组列表中添加属性名称,例如 {city,dateOfBirth},并在另一个数组列表中添加属性值,例如 {Santa Ana, 1970-01-01} 有什么建议,请帮忙!

【问题讨论】:

  • 您究竟需要什么帮助?
  • 你需要使用 SAX 解析器

标签: java xml string


【解决方案1】:
  1. 创建SAXParserFactory
  2. 创建SAXParser
  3. 创建YourHandler,扩展DefaultHandler
  4. 使用SAXParserYourHandler 解析您的文件。

例如:

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

有关 SAX 解析器和 DefaultHandler herehere 的更多信息。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 2011-04-23
      • 2012-05-13
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多