简体   繁体   中英

Parse XML character for specific attribute value using Stax Parser

XML File where I want to get Character corresponding to attribute name="Fire" which is Tree:

<Troupe name="Ring">Hat</Troupe>
<Troupe name="Fire">Tree</Troupe>
<Troupe name="bank">Next</Troupe>

Using StAX:

XmlStreamConstant.Start_Element:
   //Parse Troupe found matching attribute name whose value is Fire
XmlStreamConstant.Characters:
   //Fetch the character Tree corresponding to attribute name Fire.

Does StAX provide an easy way to fetch characters where attributes value matches a specific one?

Welcome to SO. You can get the value by :

public static void main(String[] args) {

        boolean troupe = false;

        try {

            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLEventReader eventReader =
                    factory.createXMLEventReader(new ileReader("file.xml"));

            while(eventReader.hasNext()){

                XMLEvent event = eventReader.nextEvent();

                if(event.getEventType() == XMLStreamConstants.START_ELEMENT){
                    StartElement startElement = event.asStartElement();

                    if (startElement.getName().getLocalPart().equalsIgnoreCase("Troupe")) {
                        Iterator<Attribute> attributes = startElement.getAttributes();
                        String name = attributes.next().getValue();
                        if(name.equals("Fire")) {
                            troupe = true;
                        }
                    }
                }
                else if(event.getEventType() == XMLStreamConstants.CHARACTERS) {
                    Characters characters = event.asCharacters();
                    if(troupe){
                        System.out.println("Value: "  + characters.getData());
                        troupe = false;
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
    }

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