1

给定以下 XML:

<list version="1.0">
    <meta>...</meta>
    <resources start="0" count="167">
        <resource classname="Quote">
            <field name="name">USD/KRW</field>
            <field name="price">1024.400024</field>
            <field name="symbol">KRW=X</field>
        </resource>
        ...
     </resources>
</list>

为了找到正确的<resource>并得到它,price我执行以下操作:

def slurper = new XmlSlurper()
def result = slurper.parse(XML_URL)
def node = result.depthFirst().find { it.text() == "KRW=X" }
println node.parent().find { it['@name'] == "price" }.text()

但是结果是parent()没有实现find(Closure)与文档不完全匹配:http: //groovy.codehaus.org/gapi/groovy/util/slurpersupport/GPathResult.html

node.parent().size()当我期望它按照上面的 XML 返回 3 时,更奇怪的返回 1

我的问题:

  1. 我的代码是否正确,为什么不工作?

  2. 这是实现预期结果的最短途径吗?

  3. 为什么node.parent().size()返回 1 ?也一样node.parent().parent().size()node.parent().parent().parent().size()以此类推……

4

3 回答 3

1

你能试一下吗

def resource = result.'**'.find { 
    it.field.@name == 'symbol' &&
    it.field.text() == 'KRW=X'
}

println resource?.'**'.find {
    it.@name == 'price'
}?.text()
于 2014-07-23T20:09:03.500 回答
0

一些快速而肮脏的东西,但这应该有效:

new XmlSlurper().parseText("""
<list version="1.0">
    <meta>...</meta>
    <resources start="0" count="167">
        <resource classname="Quote">
            <field name="name">USD/KRW</field>
            <field name="price">1024.400024</field>
            <field name="symbol">KRW=X</field>
        </resource>

        <resource classname="Quote">
            <field name="name">USD/KRW</field>
            <field name="price">2222</field>
            <field name="symbol">KRW=Y</field>
        </resource>

     </resources>
</list>
""").resources.resource.find{ 
    it.field.find {it.@name == "symbol" && it.text() == "KRW=X"}
}.field.find {it.@name == "price"}.text()
于 2014-07-23T20:10:26.760 回答
0

您可以使用:

def desiredPrice = new XmlSlurper().parse( XML_URL ).'**'.findResult { 
    it.name() == 'field' && it.@name == 'symbol' && it.text() == 'KRW=X' ? 
        it.parent().field.find { it.@name == 'price' }.text() : null
}
于 2014-07-23T22:00:41.677 回答