2010-07-13 5 views
0

XML로 된 XPath (Java)를 사용하여 XML 파일을 구문 분석하고 싶습니다. 그러나 이러한 XML 파일은 웹에서만 사용할 수 있습니다. (수동으로 다운로드하는 것은 옵션이 아닙니다. 물론 처리를 위해 "다운로드"해야합니다.)웹에서 XML 가져 오기 및 구문 분석

그래서 기본적으로 내 질문은 어떻게 받아 들일 수 있습니까? ...는 URI 객체와

모든 코드, 튜토리얼 아니면 그냥 일반적인 조언을 많이 주시면 감사하겠습니다 내가 파일을 다운로드하는 사이에 SCP 또는 뭔가를 사용해야합니까 File 객체로 변환 나는 시도했다이 :

URI uri = new URI("http://www.somefiles.com/myfile.xml"); 
    InputStream is = uri.toURL().openStream(); 
    File xmlDocument = new File(uri); 

그러나 이것은 URI scheme is not "file" 오류를 나타냅니다.

답변

2

좀 더 복잡하게 만들 수도 있지만 URL의 opening a stream처럼 간단 할 수 있습니다.

InputStream in = remoteURI.toURL().openStream(); 

지금이 원래 요청에 따라 File 대상이 아닌,하지만 난 당신의 XPath 라이브러리는 일반적인 InputStream을 처리 할 수 ​​있습니다 같은데요. 그렇지 않다면 위의 InputStream을 임시 파일에 저장하고 그 위에 File 객체를 만들어야 할 것이다.

+0

"URI 체계가"파일 "이 아닙니다. eror – Ankur

+1

당신은 여전히 ​​파일 생성자에'uri'를 넘겼습니다. 대신에 InputStream'is'를 사용하여 File을 생성해야합니다. – Andy

+0

예 감사합니다. Andy – Ankur

1

첫 번째 디스크에 XML을 작성하십시오 :

File tempDir = new File(System.getProperty("java.io.tmpdir")); 
File xmlDocument = new File(tempDir, "theXml.xml"); 
InputStream in = remoteURI.toURL().openStream(); 
OutputStream out = new FileOutputStream(xmlDocument); 
int read; 
while ((read = in.read()) != -1){ 
    out.write(read); 
} 
in.close(); 
out.close(); 

을하지만, 당신은 단지 XPath를 사용하여 XML에서 일부 데이터를 가져해야하는 경우, 당신은 디스크에 아무것도 쓸 필요가 없습니다 :

InputStream in = remoteURI.toURL().openStream(); 
StreamSource source = new StreamSource(in); 
DOMResult result = new DOMResult(); 
Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
transformer.transform(source, result); 
Document document = (Document)result.getNode(); 

XPath xpath = XPathFactory.newInstance().newXPath(); 
xpath.evaluate("...", document);