검색결과 리스트
xml에 해당되는 글 5건
- 2011.07.14 android 에서 xml 을 이용해 이미지 전환 효과주기 81
- 2008.07.13 java 에서 xmlrpc 사용하기 38
- 2007.08.22 부분적으로 XSL 적용하기. 22
- 2007.07.02 웹2.0 과 framework 42
- 2006.12.16 JAVASCRIPT 에서 XML 문서 DOM,XPATH 로 파싱하기 26
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/btn_focus"/> <item android:state_enabled="false" android:drawable="@drawable/btn_off"/> <item android:state_selected="true" android:drawable="@drawable/btn_select"/> <item android:drawable="@drawable/btn_normal" /> <!-- default --> </selector> |
maven 을 이용한 android 자동 빌드환경 구성 (28) | 2012.01.25 |
---|---|
createScaledBitmap 사용시 OutOfMemoryError 가 난다면? (36) | 2011.10.20 |
android 에서 xml 을 이용한 animation 처리 (32) | 2011.07.14 |
안드로이드 ListView 에서 Holder 패턴을 이용한 View 의 재활용 (45) | 2011.06.27 |
Lazy 오목 Online! for android and web (ver 2.2 ad) (108) | 2011.02.14 |
1. rpc 란?
xmlrpc 를 알아보기전에 먼저 rpc 를 알아보자.
rpc 란 Remote Procedure Call 의 약자로 말그대로 원격지에 있는 Procedure 를 호출하는 기능을 말한다.
2. xmlrpc 란?
xmlrpc란 xml과 http 프로토콜을 바탕으로 만들어진 원격 프로시저 콜 시스템 이다.
다른 컴퓨터와 주고받을수 있는 여러 프로토콜이 있지만 방화벽이나 기타 사정으로 제약을 받는 프로토콜들이 많다. 그중 가장 유연한 프로토콜이 http 프로토콜 이다. 바로 이 http 를 이용하여 xml 형태로 데이터를 간단하게 주고 받을수 있는것이 xmlrpc 이다.
3. 준비사항
오늘 만들어볼것은 xmlrpc 서버(단독서버,서블릿서버,서블릿단독서버), 클라이언트 이다.
먼저 apache 그룹에서 제공하는 xmlrpc 라이브러리를 다운받자.
http://ws.apache.org/xmlrpc/ - xmlrpc 3.1
3.1 버젼을 다운받도록 하자.
(이전 버젼을 사용해보지는 않았지만 만들면서 다른사람이 2.0 으로 만들어 놓은 예제에 3.1 라이브러리를 임포트 시켰더니 오류가 나는것을 봤을때 호환되지 않는거 같다.)
다음은 xmlrpc 라이브러리 실행에 필요한 라이브러리인데 xmlrpc 홈페이지 어디에도 이같은 라이브러리가 필요하다고 명시되어있지 않아서 삽질좀 했다.-_-;
아래 두 라이브러리를 다운받자
http://hc.apache.org - commons-httpclient 3.1
http://commons.apache.org/codec/ - commons-codec 1.3
이제 이클립스를 켜고 다이나믹 웹 프로젝트를 생성한다음
WebContents/lib 디렉토리에 모든 라이브러리를 넣는다.
4. 서버만들기
서버는 3가지 형태로 만들수 있다.
1) 단독서버형 - 이것은 톰켓의 도움없이 단독으로 실행해서 xmlrpc 서비스를 해 줄수있는 서버이다.
2) 서블릿서버형 - 이것은 톰켓의 서블릿에 추가해서 서비스 해 줄수있는 서버이다. 내가 생각하기에 이것이 가장 많이 쓰이는방법 일 거같다.
3) 서블릿단독서버형 - 이것은 1번과 2번을 합쳐놓은것인데 2번을 만들어 놓고 톰켓을 실행하지 않은상태에서 xmlrpc 만을 실행해서 서비스 해 줄수있는 방법이다.
- 먼저 서비스해줄 프로시저를 만들자.
<Calculator.java>
[code]package test;
public class Calculator {
public int add(int i1, int i2) {
return i1 + i2;
}
public int subtract(int i1, int i2) {
return i1 - i2;
}
}[/code]
- 그리고 서비스 해 줄 프로시저를 xmlrpc 라이브러리에 알려주기 위해 프로퍼티 파일을 만들자.
- 이 파일은 기본적으로 "org/apache/xmlrpc/webserver/XmlRpcServlet.properties" 디렉토리에 파일명 그대로 위치시켜야 한다.
- 이 파일의 디렉토리와 파일명은 XmlRpcServlet 클래스의 newXmlRpcHandlerMapping 메소드를 오버라이드 해서 변경할수 있지만 이렇게 구지 고정시켜 놓은 이유는 서블릿단독서버형 으로 실행할수 있도록 만들기 위해서이다.
<XmlRpcServlet.properties>
[code]Calculator=test.Calculator[/code]
4-1) 단독서버형
<StandaloneServer.java>
[code]package test;
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;
public class StandaloneServer {
private static final int port = 8080;
public static void main(String[] args) throws Exception {
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
/* Load handler definitions from a property file.
* The property file might look like:
* Calculator=org.apache.xmlrpc.demo.Calculator
* org.apache.xmlrpc.demo.proxy.Adder=org.apache.xmlrpc.demo.proxy.AdderImpl
*/
phm.load(Thread.currentThread().getContextClassLoader(),"org/apache/xmlrpc/webserver/XmlRpcServlet.properties");
/* You may also provide the handler classes directly,
* like this:
* phm.addHandler("Calculator",
* org.apache.xmlrpc.demo.Calculator.class);
* phm.addHandler(org.apache.xmlrpc.demo.proxy.Adder.class.getName(),
* org.apache.xmlrpc.demo.proxy.AdderImpl.class);
*/
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
}
}[/code]
- 애플리케이션으로 실행하면 xmlrpc 서비스 주소는 http://127.0.0.1:8080 이 된다.
4-2) 서블릿서버형
- servlet 클래스를 따로 만드는게 아니라 제공되는 클래스를만 끌어다 쓰면 바로 설정된다. 단 properties 파일은 제위치에 있어야 한다.
- web.xml 파일에 아래 설정을 추가한다.
<web.xml>
[code]<servlet>
<servlet-name>XmlRpcServlet</servlet-name>
<servlet-class>org.apache.xmlrpc.webserver.XmlRpcServlet</servlet-class>
<init-param>
<param-name>enabledForExtensions</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>XmlRpcServlet</servlet-name>
<url-pattern>/xmlrpc</url-pattern>
</servlet-mapping>[/code]
- 톰켓을 실행하면 xmlrpc 서비스주소는 http://[톰켓서버]:[톰켓포트]/[톰켓어플리케이션]/xmlrpc 가 된다.
4-3) 서블릿단독서버형
-> 이것은 4-2 가 셋팅되어있어야지 실행할 수 있다.
<ServletStandaloneServer.java>
[code]package test;
import org.apache.xmlrpc.webserver.ServletWebServer;
import org.apache.xmlrpc.webserver.XmlRpcServlet;
public class ServletStandaloneServer {
private static final int port = 8080;
public static void main(String[] args) throws Exception {
XmlRpcServlet servlet = new XmlRpcServlet();
ServletWebServer webServer = new ServletWebServer(servlet, port);
webServer.start();
}
}[/code]
- 애플리케이션으로 실행하면 xmlrpc 서비스 주소는 http://127.0.0.1:8080 이 된다.
5. 클라이언트만들기
위의 서버들이 제대로 작동한다면 xmlrpc 서비스 주소를 얻을수 있을것이다.
이제 이 주소만 있으면 인터넷이 되는 어디서든 내 서비스를 받을수 있게 되는것이다.
- 클라이언트파일만들기
<Client.java>
[code]package test;
import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
public class Client {
public static void main(String[] args) throws Exception {
// create configuration
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://127.0.0.1:8080/XMLRPCTest/xmlrpc"));
config.setEnabledForExtensions(true);
config.setConnectionTimeout(60 * 1000);
config.setReplyTimeout(60 * 1000);
XmlRpcClient client = new XmlRpcClient();
// set configuration
client.setConfig(config);
// make the a regular call
Object[] params = new Object[] { new Integer(2), new Integer(3) };
Integer result = (Integer) client.execute("Calculator.add", params);
System.out.println("2 + 3 = " + result);
}
}[/code]
6. 실행
이제 위 세가지 서버중에 하나를 띄우고 클라이언트를 실행하면 아래와같이 원하는 결과가 나오는것을 확인할수 있습니다.
JNLP 테스트 (36) | 2010.02.14 |
---|---|
JAVA 리눅스 IP 주소 알아내기 (38) | 2008.12.02 |
apache 프로젝트의 commons-dbcp 를 이용하여 connection pool 만들기. (42) | 2008.08.15 |
annotation 주석? (43) | 2006.12.16 |
JAVA5(1.5) 달라진점! (19) | 2006.12.16 |
HTML 페이지에 부분적으로 XML/XSL 을 적용할수 있게 하는 javascript
[code] var xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async=false;
xml.load("a.xml");
var xsl = new ActiveXObject("Microsoft.XMLDOM");
xsl.async=false;
xsl.load("a.xsl");
document.write(xml.transformNode(xsl));[/code]
IE vs FF(firefox) (40) | 2008.02.12 |
---|---|
홈페이지 작성시 사용되는 스타일시트 (46) | 2008.02.04 |
XSL 엘리먼트 정리 (22) | 2007.08.22 |
텍스트 로 자바스크립트 실행하는 방법 (44) | 2007.08.01 |
xsl 에서 태그 속성 바꾸기. (23) | 2007.07.16 |
우리 포도밭 guard 를 소개합니다. (748) | 2007.07.06 |
---|---|
bean 에의한 귀차니즘 (720) | 2007.07.03 |
PDA 수리 사이트 (46) | 2007.06.09 |
천상고원 (42) | 2007.05.25 |
이거 완전 사고싶다! (677) | 2007.04.25 |
먼저 알아야 할것은 dom 으로 파싱을 하려면 파싱하려는 문서의 contextType 이 text/xml 이어야 한다는 것이다. (이것때문에 좀 고생했다..ㅡ.ㅡ;)
윗쪽에 "<?xml version="1.0" encoding="euc-kr" ?>" 이처럼 xml 선언을 해 주어도 페이지 contextType 이 text/xml 이 아니면 파싱이 안되니 주의하자. (거꾸로 이처럼 xml 선언을 안해줘도 contextType 이 text/xml 이면 파싱이 가능하다.)
이 문서에서 쓸 테스트 xml 파일을 만들어 보자.
<root>
<subtitle attr1="testattr1">
<subitem attr="testattr">item1</subitem>
<subitem>item2</subitem>
<subitem>item3</subitem>
</subtitle>
<subtitle2>test</subtitle2>
</root>
간단하다..
일단 위 파일을 XMLHttpRequest 로 받은후에 responseXML 속성을 받아서 파싱하면 되겠다.
1. subtitle 의 attr1 의 데이터 가져오기.
xmlObj.getElementsByTagName("subtitle")[0].getAttribute("attr1")
- 위와같이 하면되는데 getElementsByTagName("subtitle") 는 문서내에 있는 subtitle 라는 태그를 모두 배열에 담아 돌려준다는것을 기억하자.
2. subtitle2 의 텍스트 가져오기.
xmlObj.getElementsByTagName("subtitle2")[0].text
- 노드가 가지고있는 데이터 내용을 출력할때는 text 속성을 쓴다는것을 기억하자.
3. subtitle 하위태그로 있는 subitem 태그들을 배열로 받아보자.
xmlObj.getElementsByTagName("subtitle")[0].childNodes
- 위와같이 하면 된다. 현재 테스트 문서에 subitem 은 3개 있으니 .length = 3 이 되겠다.
4. 그럼 간단하게 subitem 의 모든내용을 출력하는 것을 만들어보자.
var nodes = xmlObj.getElementsByTagName("subtitle")[0].childNodes;
for (var i=0;i<nodes.length;i++) {
alert(nodes[i].text);
}
가장 기본적인 xml 탐색방법을 알아봤다.
이걸 응용해서 어떤 것이든 탐색이 가능하겠지만 귀찮다.
그래서 나온지는 모르겠는데(ㅡ.ㅡ;) 하여튼 나온게 XPATH 이다.
자 그럼 이제 xpath 탐색법을 배워보자.
- 아래는 xpath 연산자이다.
연산자 |
의미 |
예 |
/ |
자식노드 지정 |
root/subtitle (<root>의 자식인 <subtitle>) |
// |
후손전체지정 |
root//subitem (<root>의 후손중 모든 <subitem>) |
* |
와일드카드 |
root/* (<book>의 모든 자식요소) root/@* (<book>의 속성전체) |
. |
자기자신 |
.//subtitle |
.. |
부모노드 |
../subtitle |
| |
노드의 논리합 |
root/subtitle|root/subtitle2 ( root/subtitle 와 root/subtitle2 을 모두 찾는다) |
- 이제 예제들을 보자.
1. root/subtitle 노드를 탐색해 보자.
xmlObj.selectSingleNode("root/subtitle")
- selectSingleNode 하면 매칭되는 노드가 여러개있어도 그중 최상위 하나만 돌려준다.
모두 검색하려면 selectNodes(xpath) 를 쓰면 된다.
2. 이제 getElementsByTagName() 처럼 모든 태그를 검색해서 원하는 노드를 가지고오는 것을 해보자.
xmlObj.selectSingleNode("//subtitle")
- 위와같이 "//" 연산자를 쓰게되면 해당 노드의 하위를 검색해서 일치하는 이름의 노드를 돌려준다.
- "//" 연산자는 어디든 올수있다. 예를들어 "root//subtitle" 라고 검색을 하게되면 root 이하의 노드에서 subtitle 를 찾게되는것이다.
- 단 "//" 연산자는 쓰기는 편하나 xml 파일이 커질수록 부하가 늘어난다는점을 기억하자.
3. 이제 좀더 나가서 subtitle 의 subitem 중 item2 라는 데이터값을 가지고있는 노드를 검색해보자.
xmlObj.selectNodes("/root/subtitle/subitem[.='item2']")
- 이거 놀랍지 않은가? for 문 같은거 안써도 된다..ㅡ.ㅡ;;
- item 값옆에 [] 를 쓰고 해당 데이터값을 기준으로 검색할수가 있다.
- 여기서 '.' 은 자기 자신을 의미한다.
4. subtitle 의 subitem 중 attr 속성이 'testattr' 인것을 검색해보자.
xmlObj.selectNodes("/root/subtitle/subitem[@attr='item2']")
- '@' 요걸 쓰면 된다.
- 단 [] 구문은 / 옆이 아니라 item 이름 옆에 온다는것을 기억하자.
5. 이제 좀헷깔리는 문제를 보자. 아래두 구문의 차이는 무엇일까?
xmlObj.selectNodes("/root/subtitle[subitem='item2']")
xmlObj.selectNodes("/root/subtitle/subitem[.='item2']")
- 둘다 subitem 의 데이터를 검색하긴 한다 그러나 위에것은 subtitle 노드를 돌려주고 아래것은 subitem 노드를 돌려준다.
- [] 구문은 바로 옆에 있는 노드를 돌려준다는것을 기억하자.
6. 자 아래 구문을 보자.
xmlObj.selectNodes("/root/subtitle/subitem/@*");
- 어떤 노드의 속성을 모두 탐색하고 싶다면 위와같이 하면 된다.
- 속성이 속성값이 아니라 하나의 노드로 인식해서 돌려주게된다.
- 위의 내용은 subitem 에 속성은 attr 밖에 없으니까 attr 노드를 돌려주게 되는것이다.
- 소스로 설명하면 아래와 같다.
<subitem attr="testattr"/>
위의 소스를
<subitem>
<attr>testattr</attr>
</subitem>
위와같이 인식하는 것이다.
부분적으로 XSL 적용하기. (22) | 2007.08.22 |
---|---|
XSL 엘리먼트 정리 (22) | 2007.08.22 |
텍스트 로 자바스크립트 실행하는 방법 (44) | 2007.08.01 |
xsl 에서 태그 속성 바꾸기. (23) | 2007.07.16 |
웹페이지 인코딩 (23) | 2007.06.11 |
RECENT COMMENT