Eine Möglichkeit, dies zu erreichen, ist die Verwendung des im JDK enthaltenen DOM-Parsers. Zum Beispiel:
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
...
// Creates a new DOM parser instance.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Parses XML and creates a DOM document object.
// The XML variable is your XML document above stored as a string, but you could
// easily read the contents from a file or database too.
Document document = documentBuilder.parse(new InputSource(new StringReader(XML)));
// Get the text content of <theatername> using the DOM API and print it to stdout.
String theaterName = document.getElementsByTagName("theatername").item(0).getTextContent().trim();
System.out.println(theaterName);
Mit StAX:
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(XML));
String theaterName = null;
while (xmlStreamReader.hasNext()) {
if (xmlStreamReader.next() == XMLStreamConstants.START_ELEMENT) {
if ("theatername".equals(xmlStreamReader.getLocalName())) {
theaterName = xmlStreamReader.getElementText().trim();
}
}
}
System.out.println(theaterName);
Die kurze Antwort ist, dass Sie nicht können, da der Eingang Sie zeigen nicht gültige XML und nicht als XML durch einen XML-Parser analysiert werden kann (in jedem Sprache). Es ist nicht gültig, da es mehrere Wurzelelemente hat. Sie müssen dies in mehrere Dateien aufteilen, bevor Sie es als XML analysieren. –
Bitte posten Sie das ** genaue ** erwartete Ergebnis (als Code). –