代码之家  ›  专栏  ›  技术社区  ›  user22946701

将列表中的每个元素封装为平面文件中的新行

  •  0
  • user22946701  · 技术社区  · 2 年前

    我正试图将以下xml中的所有值转换为一个由“|”分隔的字符串

    <n0:SendData xmlns:n0="http://testdata/"
                     xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
        <Operation>Testing1</Operation>
        <InputDataList>
            <InputData>
                <Field>ATTRIBUTE1</Field>
                <Value>1.000</Value>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE2</Field>
                <Value>test</Value>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE3</Field>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE4</Field>
                <Value>testend</Value>
            </InputData>
        </InputDataList>
        <InputDataList>
            <InputData>
                <Field>ATTRIBUTE1</Field>
                <Value>2.000</Value>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE2</Field>
                <Value>test2</Value>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE3</Field>
                <Value>test2end</Value>
            </InputData>
            <InputData>
                <Field>ATTRIBUTE4</Field>
            </InputData>
        </InputDataList>
    </n0:SendData>
    

    我想出的代码:

    def xml = new XmlSlurper().parseText(data)
    
    def items = xml.InputDataList.each { node ->
        node.InputData.Field.text() == ""
    }.collect { node ->
        node.InputData.with {
            "${InputData.text()}|\n"
        }
    }
    
    println items
    

    这将导致以下响应

    1.000测试结束|

    2000测试2测试2|

    但是,即使值为空,我也找不到在列表的每个元素后面添加“|”的方法?

    我想要的结果如下

    1.000|测试||测试结束

    2.000|test2|test2end||

    0 回复  |  直到 2 年前
        1
  •  0
  •   cfrick    2 年前

    你想 collect 这个 Value 每个的s InputDataList , join 他们 具有 | :

    def items = xml.InputDataList.collect { node ->
            node.InputData*.Value.join("|")
    }.join("\n")
    

    这个 each 在你最初的尝试中,是一个无操作,因为比较 那里只会给你的房间供暖。你想吗 findAll 相反