XML文件我希望得到的字符对应于属性名称=" Fire"这是树:
<Troupe name="Ring">Hat</Troupe>
<Troupe name="Fire">Tree</Troupe>
<Troupe name="bank">Next</Troupe>
使用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.
StAX是否提供了一种简单的方法来获取属性值与特定值匹配的字符?
答案 0 :(得分:0)
欢迎来到SO。 您可以通过以下方式获取价值:
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();
}
}