我使用groovy来使用XmlParser解析XML文件。为了避免处理名称空间前缀,我使用xmlRoot。'**'。findAll()方法来查找一些节点。示例代码显示了它如何正常工作,直到我只读取节点,因为传递给闭包的每个项都是一个Node对象。但是当我更改节点的内容(在这种情况下,只是节点的文本)时,对findAll的下一次调用不会迭代Node对象。对于我放入文本的每个字符,String对象被传递给闭包。我解决了用instanceof检查类型,但似乎这是一个错误。
我做错了什么或者是个错误?
class XmlParserTest {
static final String XML_SAMPLE = """
<ns0:root xmlns:ns0="mycompany.com">
<ns0:firstParent>
<ns0:item1>uppercase_me!</ns0:item1>
</ns0:firstParent>
<ns0:secondParent>
<ns0:item2>uppercase_me_too!/ns0:item2>
</ns0:secondParent>
</ns0:root>
"""
static void main(String[] args) {
def xmlRoot = new XmlParser(false, false).parseText(XML_SAMPLE)
//******* find item1 and capitalize its text ********
def nds1 = xmlRoot.'**'.findAll {
it.name().equals("ns0:item1")
}
Node nd1 = nds1[0]
//This changes the text of the node, but something strange happens to the node tree
nd1.setValue(nd1.value().toString().toUpperCase())
//The same problem happens using replaceNode() instead of setValue()
//Node newNode = new Node(nd1.parent(), nd1.name(), nd1.value().toString().toUpperCase())
//nd1.replaceNode(newNode)
//******* find item2 and capitalize its text ********
def nds2 = xmlRoot.'**'.findAll {
//for each character in the string "uppercase me!" a String is passed instead of Node
//As String doesn't have a name method, an exception is raised
it.name().equals("ns0:item2")
//using instanceof fixes the problem, at least for this case
it instanceof Node && it.name().equals("ns0:item2")
}
Node nd2 = nds2[0]
nd2.setValue(nd2.value().toString().toUpperCase())
assert nd1.value().toString() == nd1.value().toString().toUpperCase()
assert nd2.value().toString() == nd2.value().toString().toUpperCase()
}
}
我在Groovy上打开了一个问题:this is the explation on what happened