簡體   English   中英

Groovy腳本中的XMLSlurper無法用於簡單的XML

[英]XMLSlurper inside Groovy Script Not Working for a simple XML

我正在嘗試使用Groovy Script的XMLSlurper插件解析XML。 我需要讀取d:editStatus元素中的值。

import groovy.xml.*;
def myxml = '<?xml version="1.0" encoding="utf-8"?>' +
'<feed xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">' +
    '<entry>' +
        '<content type="application/xml">' +
            '<m:properties>' +
                '<d:key>JobApplication/applicationId=94319</d:key>' +
                '<d:status>OK</d:status>' +
                '<d:editStatus>UPDATED</d:editStatus>' +
                '<d:message>Application has been updated successfully</d:message>' +
                '<d:index m:type="Edm.Int32">0</d:index>' +
                '<d:httpCode m:type="Edm.Int32">204</d:httpCode>' +
                '<d:inlineResults m:type="Bag(SFOData.UpsertResult)"></d:inlineResults>' +
            '</m:properties>' +
        '</content>' +
    '</entry>' +
    '</feed>'


def mystatus = new XmlSlurper().parseText(myxml)

println mystatus

在這里,輸出應該已經顯示了xml的對象形式,但是它給了我以下輸出

JobApplication/applicationId=94319OKUPDATEDApplication has been updated successfully0204

這很奇怪,因為我看不到任何元素,它正在連接所有值並顯示為輸出。 我無法獲取單個元素。

默認情況下,打印出GPathResult的值將打印出其節點的所有值。

要提取單個節點的值:

import groovy.xml.*

def myxml = '''
    <feed xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
        <entry>
            <content type="application/xml">
                <m:properties>
                    <d:key>JobApplication/applicationId=94319</d:key>
                    <d:status>OK</d:status>
                    <d:editStatus>UPDATED</d:editStatus>
                    <d:message>Application has been updated successfully</d:message>
                    <d:index m:type="Edm.Int32">0</d:index>
                    <d:httpCode m:type="Edm.Int32">204</d:httpCode>
                    <d:inlineResults m:type="Bag(SFOData.UpsertResult)"></d:inlineResults>
                </m:properties>
            </content>
        </entry>
    </feed>
'''


def xml = new XmlSlurper().parseText(myxml)

println "key: ${xml.entry.content.properties.key}"
println "status: ${xml.entry.content.properties.status}"
println "editStatus: ${xml.entry.content.properties.editStatus}"
println "message: ${xml.entry.content.properties.message}"
println "index: ${xml.entry.content.properties.index}"
println "httpCode: ${xml.entry.content.properties.httpCode}"
println "inlineResults: ${xml.entry.content.properties.inlineResults}"

您也可以使用@提取節點屬性的值

println xml.entry.content.@type

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM