I am using XMLStreamReader
to read an XML file and look for a specific element then update the corresponding value.
My question is that is there a way I can print each element, including the start of the document such as:
<?xml version="1.0" encoding="UTF-8"?>
every time I do reader.next()
?
For example:
XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(
file));
while(reader.hasNext())
reader.next().ToString() //Something like this?
...
I am a little confused about what you are asking.
To print the <?xml version="1.0" encoding="UTF-8"?>
you will have to handle the START_DOCUMENT
event. You can call the following methods for this state:
next(), getEncoding(), getVersion(), isStandalone(), standaloneSet(), getCharacterEncodingScheme(), nextTag()
To print the name of the element that was most previously read whenever you do a next()
call:
XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(
file));
String currentElement = "";
while(reader.hasNext()) {
int next = reader.next();
..
if(next == XMLStreamReader.START_ELEMENT){
currentElement = reader.getLocalName();
..
System.out.println(currentElement );
}
Or, if you are interested in just printing out all of the data from the XML file, you need to handle each event accordingly:
XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(
file));
while(reader.hasNext()) {
int next = reader.next();
..
if(next == XMLStreamReader.START_ELEMENT){
System.out.println(reader.getLocalName());
}
else if(next == XMLStreamReader.ATTRIBUTE) {
// Print out all the attributes
}
else if(next == XMLStreamReader.COMMENT) {
// Print the comment
}
..
}
For a full list of events, reference the documentation .
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.