달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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);
        }
}
}


 

:
Posted by mastar