Scala从序列后面的String中删除字符

时间:2017-07-04 11:14:18

标签: java string scala

我编写了一个将xml转换为json的示例程序。但我想删除后跟序列的字符。如何实现它。

在下面的示例中,我想在字符串中删除“tns:”,如果它出现在“<”之后字符。

object example {
def main(args: Array[String]): Unit = {
  val xmldata :String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tns:createGroup xmlns:tns=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05 sample.xsd \">\n  <tns:customerGroup>\n    <tns:groupTypeCode>100</tns:groupTypeCode>\n    <tns:groupTypeDescription>sampleGroup</tns:groupTypeDescription>\n    <tns:groupAccountNumber>100100234</tns:groupAccountNumber>\n    <tns:groupName>sampleName</tns:groupName>\n    <tns:status>open</tns:status>\n    <tns:memberCountThreshold>3</tns:memberCountThreshold>\n    <tns:guestCountThreshold>4</tns:guestCountThreshold>\n    <tns:creatorDetails>\n      <tns:membershipNumber>00800934564</tns:membershipNumber>\n      <tns:mediaCode>400</tns:mediaCode>\n    </tns:creatorDetails>\n    <tns:createdDate>03JUL2017</tns:createdDate>\n    <tns:MilesSummary/>\n  </tns:customerGroup>\n  <tns:error>\n    <tns:errorRecord>noerror</tns:errorRecord>\n  </tns:error>\n</tns:createGroup>\n"
  val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata)
  val miles = (loyaltyGroupMessageXML \\ "customerGroup")
  //print(miles)
  val json = toJson(miles)
  //val parsed = parse(json)
  //print(parsed)
  print(pretty(render(json)))
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用replace功能

xmldata.replace("<tns:", "<")

您可以在代码中使用它

val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<"))

您仍需要将结尾</tns:替换为</。为此你可以做到

xmldata.replace("<tns:", "<").replace("</tns:", "</")

在您的代码中

val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<").replace("</tns:", "</"))