0

Recently I started using XML more and now I'm stuck on a weird problem that I can't find a solution to anywhere. How do you read an attribute from a characters event in? I'll show you the XML code and a snippet of the Java code below.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <entity id="Player">
        <state>MainMenu</state>
        <attr id="health">10</attr>
        <attr id="inventory">axe</attr>
        <controller>0</controller>
    </entity>
</config>

Java:

if (event.asStartElement().getName().getLocalPart().equals("attr"))
{
    event = eventReader.nextEvent();

    System.out.println("Attr: " + event.asCharacters().toString()); 
    System.out.println();

    // Iterator<Attribute> attributes = event.asStartElement().getAttributes();

    /*while (attributes.hasNext())
    {
        Attribute attribute = attributes.next();
        if (attribute.getName().toString().equals("id"))
        {
            e.addAttribute(attribute.getValue(), event.asCharacters().getData());
        }
    }*/

    continue;
}
robertoia
  • 2,301
  • 23
  • 29
KBoiii
  • 1

1 Answers1

1

As far as I can tell, you can't. I don't think it even makes sense. An attribute event is not a characters event, so you shouldn't be able to use asCharacters() on it successfully at all.

You are meant to pick out the XMLEvent representing the start of the element of interest, use asStartElement() to get a view of it as a javax.xml.stream.events.StartElement, and examine its attributes via either StartElement.getAttributeByName() or StartElement.getAttributes().

John Bollinger
  • 160,171
  • 8
  • 81
  • 157