2016-06-15 2 views
-3

은 내가 태그 서버 이름 및 theatername의 값을 원하는 xml에서 지정된 뿌리를 얻는 방법?

<?xml version="1.0" encoding="utf-8"?> 
 
<Movies> 
 
    <servername> 
 
      raaja 
 
    </servername> 
 
    <moviename> 
 
      xyz 
 
    </moviename> 
 
    <city> 
 
      Hyd 
 
    </city> 
 
    <theatername> 
 
      abc 
 
    </theatername> 
 
    <noofreels> 
 
      16 
 
    </noofreels> 
 
    <aspectratio> 
 
     216 
 
    </aspectratio> 
 
</Movies>

아래와 같은 XML 파일이 있습니다. 나는 원하지 않는다. 자바를 사용하여 이들을 얻는 방법. tagnames를 사용하여 값을 얻을 수 있습니까?

+0

짧은 대답은 당신이 보여 입력이 유효한 XML이 아닙니다 할 수 없기 때문이다 어떤에서 (XML 파서로 XML로 구문 분석 할 수 없습니다 언어). 루트 요소가 여러 개이기 때문에 유효하지 않습니다. XML로 파싱하기 전에이를 여러 파일로 나눠야합니다. –

+0

** 정확한 ** 예상 결과 (코드)를 게시하십시오. –

답변

1

이 작업을 수행하는 한 가지 방법은 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); 
+0

stax를 사용하여 구현하는 방법은 무엇입니까? – vamsi

관련 문제