2010-06-14 3 views
0

특정 XmlSlurper 태그를 임의의 XML 문자열로 바꾸려고합니다. 내가 관리해야 가장 좋은 방법은 이것이다 할 가지고 올!임의의 XML로 XmlSlurper 태그 바꾸기

# 그루비는/usr/빈/ENV

import groovy.xml.StreamingMarkupBuilder 

def page=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(""" 
<html> 
<head></head> 
<body> 
<one attr1='val1'>asdf</one> 
<two /> 
<replacemewithxml /> 
</body> 
</html> 
""".trim()) 

import groovy.xml.XmlUtil 

def closure 
closure={ bind,node-> 
    if (node.name()=="REPLACEMEWITHXML") { 
    bind.mkp.yieldUnescaped "<replacementxml>sometext</replacementxml>" 
    } else { 
    bind."${node.name()}"(node.attributes()) { 
     mkp.yield node.text() 
     node.children().each { child-> 
closure(bind,child) 
     } 
    } 
    } 
} 
println XmlUtil.serialize(
    new StreamingMarkupBuilder().bind { bind-> 
    closure(bind,page) 
    } 
) 

그러나, 유일한 문제는 텍스트입니다() 요소는 을 캡처하는 것 모든 자식 텍스트 노드 및 따라서 내가 얻을 :

<?xml version="1.0" encoding="UTF-8"?> 
<HTML>asdf<HEAD/> 
    <BODY>asdf<ONE attr1="val1">asdf</ONE> 
     <TWO/> 
     <replacementxml>sometext</replacementxml> 
    </BODY> 
</HTML> 

모든 아이디어가/많이 감사합니다 도움이됩니다.

감사합니다. 미샤

p.s. 또한 호기심 때문에, 위의 "Groovier"표기법을 다음과 같이 변경하면 Groovy 컴파일러는 내 테스트 클래스의 $ {node.name()} 멤버에 액세스하려고한다고 생각합니다. 실제 빌더 객체를 전달하지 않는 경우에이를 지정하는 방법이 있습니까? 고맙습니다! :) 여기 좋아

def closure 
closure={ node-> 
    if (node.name()=="REPLACEMEWITHXML") { 
    mkp.yieldUnescaped "<replacementxml>sometext</replacementxml>" 
    } else { 
    "${node.name()}"(node.attributes()) { 
     mkp.yield node.text() 
     node.children().each { child-> 
closure(child) 
     } 
    } 
    } 
} 
println XmlUtil.serialize(
    new StreamingMarkupBuilder().bind { 
    closure(page) 
    } 
) 

답변

0

내가 생각 해낸 것입니다 :

#!/usr/bin/env groovy 

import groovy.xml.StreamingMarkupBuilder 
import groovy.xml.XmlUtil 

def printSlurper={page-> 
    println XmlUtil.serialize(
    new StreamingMarkupBuilder().bind { bind-> 
     mkp.yield page 
    } 
) 
} 
def saxParser=new org.cyberneko.html.parsers.SAXParser() 
saxParser.setFeature('http://xml.org/sax/features/namespaces',false) 
saxParser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",true) 

def string="TEST" 
def middleClosureHelper={ builder-> 
    builder."${string}" { 
    mkp.yieldUnescaped "<inner>XML</inner>" 
    } 
} 

def middleClosure={ 
    MiddleClosure { 
    middleClosureHelper(delegate) 
    } 
} 

def original=new XmlSlurper(saxParser).parseText(""" 
<original> 
<middle> 
</middle> 
</original> 
""") 

original.depthFirst().find { it.name()=='MIDDLE' }.replaceNode { node-> 
    mkp.yield middleClosure 
} 

printSlurper(original) 

assert original.depthFirst().find { it.name()=='INNER' } == null 
def modified=new XmlSlurper(saxParser).parseText(new StreamingMarkupBuilder().bind {mkp.yield original}.toString()) 
assert modified.depthFirst().find { it.name()=='INNER' } != null 

당신은 slurper를 다시로드해야하지만 작동!

Misha