xml - 如何解析文件夹中的 XML 文件以映射 String,List<String>

标签 xml parsing dictionary groovy

我正在尝试解析文件夹中的多个 XML 文件,并从每个文件中检索 String、List 的映射。我在分离值时遇到问题。

//### XML 文件结构示例

 <fields>
    <fullName>DandbCompanyId</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>Lookup</type>
</fields>
<fields>
    <fullName>Description</fullName>
    <trackFeedHistory>false</trackFeedHistory>
</fields>
<fields>
    <fullName>DunsNumber</fullName>
    <trackFeedHistory>false</trackFeedHistory>
</fields>
<fields>
    <fullName>Fax</fullName>
    <trackFeedHistory>false</trackFeedHistory>
</fields>
<fields>
    <fullName>Industry</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>Picklist</type>
</fields>
<fields>
    <fullName>IsCustomerPortal</fullName>
</fields>
<fields>
    <fullName>IsPartner</fullName>
    <trackFeedHistory>false</trackFeedHistory>
</fields>
<listViews>
    <fullName>AllAccounts</fullName>
    <filterScope>Everything</filterScope>
    <label>All Accounts</label>
</listViews>
<listViews>
    <fullName>MyAccounts</fullName>
    <filterScope>Mine</filterScope>
    <label>My Accounts</label>
</listViews>

//#### 这就是我所拥有的

String srcPath = this.args[0];
def objFolder = new File(srcPath + '/objects')
if(!objFolder || !objFolder.isDirectory()) {
    println " ####  ERROR: ${objFolder} doesn't exist or is not a folder"
    return
} else {
    println " ####  Path is correct! Checking objects"
}

def objMap = [:]

def xs = new XmlSlurper()

objFolder.eachFile { file ->
    objMap.put(file.getName().split("\\.")[0], xs.parse(file).fields.fullName.each{
        it.@fullName
    })
};

objMap.each { k,v -> println v}

//### 这是输出

DescriptionIsAlohaSupportedIsLightningSupportedNameOwnerIdStartingContext

IndustryOwnership
AllocationIdAmountBudgetIdChannelPartnerIdDescriptionOwnerIdRequestIdStatusTitle
ScorecardIdTargetEntityId

ActivityAllocationIdAmountBudgetIdCampaignIdChannelPartnerIdDescriptionDesiredOutcomeOwnerIdRequestedAmountStatusTitleTotalApprovedFcsTotalReimbursedFcs
CategoriesStatus

CapturedAngleContentDocumentIdImageAlternateTextImageClassImageClassObjectTypeImageTitleImageUrlImageViewTypeIsActiveName
Role

我的目标是实现以下结果:

地点 ID、金额、预算 ID、 channel

所以它应该看起来像一个字符串列表(在 map 中它将是值)

最佳答案

您尝试的操作存在两个问题。

第一个是使用 each它对集合中的每个项目执行操作,但返回原始集合(不是操作的结果 - 为此,您需要 collect )

第二个是it.@fullName将返回属性 fullName在标签上(即:如果您有 <node fullName="something">...</node> ),而您只需要 text()节点的

所以以下内容会起作用:

xs.parse(file).fields.fullName.collect { it.text() }

但是在 Groovy 中,我们可以缩短这个 collect使用扩展运算符 * ,这给了我们更短的:

xs.parse(file).fields.fullName*.text()

玩得开心!

关于xml - 如何解析文件夹中的 XML 文件以映射 String,List<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543903/

相关文章:

c# - Long.Tryparse 重载和转换错误 C#

ios - 如何在 iOS 上读取或解析 .mobi 文件

c++ - 多维锯齿状图

java - 如何将映射的键设置为变量名

cricinfo记分卡的html解析

sql 设置 xml 值

java - 转换JSON日期格式

C++ STL 错误的键类型

xml - 使用xpath在svg下找到第n个 child

android - 在 android 中不使用 findViewById() 查找所有微调器 View