简体   繁体   English

如何从 Scala 中的“#PCDATA”获取数据?

[英]How do I get the data from "#PCDATA" in Scala?

def loadXml(node: Node): Unit = {

  val children = node.child

  children.foreach(child => {
    var tag = child.label

    //if owner tag, load the owen
    if (tag == "zip")
    {
      loadZipXML(child)
    }
    else if (tag == "owner")
    {
      //if owner tag, make a new pet and have it load the info it wants, then add it to the list
      val owner = Owner()
      owner.loadXml(child)
      insurance += owner
    }
  })
}

I have the following code and I'm feeding it this XML:我有以下代码,我正在向它提供这个 XML:

<?xml version='1.0' encoding='UTF-8'?>
<insurance>
    <zip code="57701">
        <owner name="Harold">
        </owner>
        <owner name="Bob">
        </owner>
        <owner name="Indiana Jones">
        </owner>
        <owner name="Darth Vader">
        </owner>
    </zip>
    <zip code="57702">
        <owner name="Sue">
        </owner>
        <owner name="Captain Kirk">
        </owner>
    </zip>
    <zip code="57703">
    </zip>
</insurance>

I can pull the zip code fine.我可以很好地提取邮政编码。 But every time I get owner the label becomes #PCDATA.但是每次我获得所有者时,标签都会变成#PCDATA。 I know that means that its a child with more data, but how do I grab that label and then keep traversing the XML file?我知道这意味着它是一个拥有更多数据的孩子,但是我如何获取该标签然后继续遍历 XML 文件?

Not sure why you need the XML label, but it sounds like you're trying to marshal the data in to an "owner" data structure.不确定您为什么需要 XML 标签,但听起来您正试图将数据编组到“所有者”数据结构中。 For example, consider this "owner" class:例如,考虑这个“所有者”类:

final case class Owner(
  label: String, 
  name:  String, 
  text:  String, 
  zip:   String)

I'd probably iterate through the XML as:我可能会遍历 XML:

val insurance = scala.xml.XML.load("insurance.xml")
val owners = 
  for {
    zip   <- insurance \ "zip"
    owner <- zip \ "owner"
  } yield {
    Owner(
      label = owner.label, 
      name  = owner \@ "name",
      text  = owner.text.trim,
      zip   = zip \@ "code"
    )
  }

Printing the file:打印文件:

owners.foreach(println)

Outputs:输出:

Owner(owner,Harold,,57701)
    Owner(owner,Bob,,57701)
    Owner(owner,Indiana Jones,,57701)
    Owner(owner,Darth Vader,,57701)
    Owner(owner,Sue,,57702)
    Owner(owner,Captain Kirk,,57702)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM