如何使用Groovy Markup Builder向元素添加名称空间和前缀

时间:2015-04-27 17:49:53

标签: xml soap groovy mule

我正在使用Mule ESB将输入JSON转换为XML以发送到SOAP Web服务。我能够构建结构并向根元素添加名称空间,但我的SOAP需要的XML输出非常精确,并要求元素中的前缀和名称空间。

这是我的Groovy脚本:

//td[preceding-sibling::td[. = 'NotProvisioned']]//a[. = 'Examine']

以下是它给我的输出示例:

def xml = new StringWriter().with { w -> new groovy.xml.MarkupBuilder(w).with {
        SaveContact('http://tempuri.org/') {
            contact() {  
                Address('http://schemas.datacontract.org/2004/07/PivotalService.Entities')   
                {
                    Address1(payload.Address1)
                    Address2(payload.Address2)
                    Address3(payload.Address3)
                    City(payload.City)
                    Country(payload.Country)
                    Fax(payload.Fax)
                    Mobile(payload.Mobile)
                    Phone(payload.Phone)
                    PhoneExtension(payload.PhoneExtension)
                    State(payload.State)
                    Workphone(payload.Workphone)
                    WorkphoneExtension(payload.WorkphoneExtension)
                    Zip(payload.Zip)
                }
                ContactId(payload.ContactId)
                Email(payload.Email)
                Firstname(payload.Firstname)
                Gender(payload.Gender)
                Language(payload.Language)
                Lastname(payload.Lastname)
                PrestashopId(payload.PrestashopId)
            }
            Consent(payload.Consent)
        }
    }
    w.toString()
}

正如您所看到的,添加到元素时,命名空间甚至不起作用。

这是我想要的XML(我不确定是否需要前缀(ns0..etc)):

<SaveContact xmlns='http://tempuri.org/'>
  <contact>
    <Address xmlns='http://schemas.datacontract.org/2004/07/PivotalService.Entities'>
      <Address1>2, test street</Address1>
      <Address2>Appartement 10</Address2>
      <Address3 />
      <City>Montreal</City>
      <Country>Canada</Country>
      <Fax />
      <Mobile>+1(418)123-1234</Mobile>
      <Phone>+1(418)123-1234</Phone>
      <PhoneExtension />
      <State>Québec</State>
      <Workphone />
      <WorkphoneExtension />
      <Zip>A1A1A1</Zip>
    </Address>
    <ContactId />
    <Email></Email>
    <Firstname>fooo</Firstname>
    <Gender>1</Gender>
    <Language>3</Language>
    <Lastname>baaarrr</Lastname>
    <PrestashopId>172</PrestashopId>
  </contact>
  <Consent></Consent>
</SaveContact>

感谢您的帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

以下实施可能很有用:

def entityNs = [
    'xmlns:ns1': "http://schemas.datacontract.org/2004/07/PivotalService.Entities"
]

继续上面的内容,例如:

....
"ns1:Email"(entityNs, 'foo')
"ns1:Firstname"(entityNs, 'Bar')
....