My goal ...">

Parsing XML strings in Java

I'm trying to parse XML String format like:

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

      

My goal is to add attribute name to array list like {city, dateOfBirth} and attribute values ​​in another array list like {Santa Ana, 1970-01-01} any advice please help!

+3


source to share


2 answers


  • Create SAXParserFactory

    .
  • Create SAXParser

    .
  • Create YourHandler

    that expands DefaultHandler

    .
  • Parse the file with 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

is a class object File

.



In the class 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;
    }
}`

      

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

+1


source


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


source







All Articles