Wikipedia StAX
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
// XML
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<root date=\"2009-01-08\" >")
.append("<!-- <<comment>> -->")
.append("<user>")
.append("<name>Solnone</name>")
.append("<birthday>1900-01-01</birthday>")
.append("</user>")
.append("<user>")
.append("<name>John</name>")
.append("<birthday>1912-02-02</birthday>")
.append("</user>")
.append("</root>");
InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
System.out.println("ENCODING: " + reader.getEncoding());
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
System.out.println("ELEMENT Name: " + reader.getName());
for (int i = 0; i < reader.getAttributeCount(); i++) {
System.out.println("ATTRIBUTE: "
+ reader.getAttributeName(i) + "="
+ reader.getAttributeValue(i));
}
break;
case XMLStreamConstants.END_ELEMENT:
System.out.println("END ELEMENT: " + reader.getName());
break;
case XMLStreamConstants.CHARACTERS:
System.out.println("TEXT: " + reader.getText());
break;
default:
if (reader.hasName()) {
System.out.println("OTHER NAME: " + reader.getText());
}
if (reader.hasText()) {
System.out.println("OTHER TEXT: " + reader.getText());
}
break;
}
}
} finally {
is.close();
}
}
}
/*
ENCODING: UTF-8
ELEMENT Name: root
ATTRIBUTE: date=2009-01-08
OTHER TEXT: <<comment>>
ELEMENT Name: user
ELEMENT Name: name
TEXT: Solnone
END ELEMENT: name
ELEMENT Name: birthday
TEXT: 1900-01-01
END ELEMENT: birthday
END ELEMENT: user
ELEMENT Name: user
ELEMENT Name: name
TEXT: John
END ELEMENT: name
ELEMENT Name: birthday
TEXT: 1912-02-02
END ELEMENT: birthday
END ELEMENT: user
END ELEMENT: root
*/
沒有留言:
張貼留言