[자바] XML 파서 getTextContent java 1.4 에서 사용하기 용-ILE/LANG-JAVA(JSP)2008. 5. 15. 19:55
http://suite.tistory.com/ 2007 11 21 fs
자바 1.5 XML 파서 API 중에 getTextContent() 함수가 꽤? 유용하다~
근데 일반 적으로 쓰는 1.4 버전에는 지원을안한다 ~~ 그렇다고~ getFirstChild() 함수나 getNodeValue() 를 이용하면
코딩줄이 늘어나기 시작한다~~
그래도 쓸려고 검색을 좀했더니
어느 착한 외국분이 구현해 두었다~~~
출처: http://www.java-answers.com/index.php?action=recent;start=60
소스를 보고 자신에 맞게 고쳐써두 잘돌아간다.
ex) CDATA 도 받을려면 if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static String getTextContent(Node node) throws DOMException
{
String textContent = "";
if (node.getNodeType() == Node.ATTRIBUTE_NODE)
{
textContent = node.getNodeValue();
}
else
{
Node child = node.getFirstChild();
if (child != null)
{
Node sibling = child.getNextSibling();
if (sibling != null)
{
StringBuffer sb = new StringBuffer();
getTextContent(node, sb);
textContent = sb.toString();
}
else
{
if (child.getNodeType() == Node.TEXT_NODE)
{
textContent = child.getNodeValue();
}
else
{
textContent = getTextContent(child);
}
}
}
}
return textContent;
}
private static void getTextContent(Node node, StringBuffer sb) throws DOMException
{
Node child = node.getFirstChild();
while (child != null)
{
if (child.getNodeType() == Node.TEXT_NODE)
{
sb.append(child.getNodeValue());
}
else
{
getTextContent(child, sb);
}
child = child.getNextSibling();
}
}
public static void setTextContent(Node node, String textContent) throws DOMException
{
if (node.getNodeType() == Node.ATTRIBUTE_NODE)
{
if (textContent == null) textContent = "";
node.setNodeValue(textContent);
}
else
{
Node child;
while ((child = node.getFirstChild()) != null)
{
node.removeChild(child);
}
if (!StringUtils.isEmpty(textContent))
{
Text textNode = node.getOwnerDocument().createTextNode(textContent);
node.appendChild(textNode);
}
}
}
'용-ILE > LANG-JAVA(JSP)' 카테고리의 다른 글
[ JSP ] C sprintf 와 같은 String.format 사용 예제 (0) | 2008.05.15 |
---|---|
[JAVA] 디렉토리 파일 리스트 읽어오기 ~ 가져오기 (0) | 2008.05.15 |
[자바] java 로 키워드 통계 랭킹 리스트 만들기 (0) | 2008.05.15 |
[ 자바 ] 한글 초성 중성 종성 숫자 수치화 (0) | 2008.05.15 |
[BLOB] 오라클 oracle blob 데이터 읽어서 파일로 저장 (0) | 2008.05.15 |