이 작업을 수행하는 한 가지 방법은 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);
은 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);
출처
2016-06-15 23:54:03
ck1
짧은 대답은 당신이 보여 입력이 유효한 XML이 아닙니다 할 수 없기 때문이다 어떤에서 (XML 파서로 XML로 구문 분석 할 수 없습니다 언어). 루트 요소가 여러 개이기 때문에 유효하지 않습니다. XML로 파싱하기 전에이를 여러 파일로 나눠야합니다. –
** 정확한 ** 예상 결과 (코드)를 게시하십시오. –