Java 如何从xml中获取指定的根?
我有如下XML文件Java 如何从xml中获取指定的根?,java,xml,xslt,Java,Xml,Xslt,我有如下XML文件 拉贾 xyz 液压 abc 16 216 实现这一点的一种方法是使用JDK附带的DOM解析器。例如: import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; ...
拉贾
xyz
液压
abc
16
216
实现这一点的一种方法是使用JDK附带的DOM解析器。例如:
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);
简而言之,您不能这样做,因为您显示的输入不是有效的XML,并且不能由XML解析器(以任何语言)解析为XML。它无效,因为它有多个根元素。在将其解析为XML之前,您需要将其拆分为多个文件。请发布准确的预期结果(作为代码)。我们如何使用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);