简体   繁体   中英

XML string parsing in Java

I am trying to parse through a XML format String for example;

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

My goal is to add attributes name in an array list such as {city,dateOfBirth} and values of the attributes in another array list such as {Santa Ana, 1970-01-01} any advice, please help!

Using 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. Create SAXParserFactory .
  2. Create SAXParser .
  3. Create YourHandler , which extends DefaultHandler .
  4. Parse your file using SAXParser and YourHandler .

For example:

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

where, yourFile - object of the File class.

In YourHandler class:

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

More information for SAX parser and DefaultHandler here and here respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM