【问题标题】:Kotlin reading children of XMLKotlin 读取 XML 的子级
【发布时间】:2021-08-12 14:40:12
【问题描述】:

我可以阅读 DeckName、NumberOfCards 和 Introduction,但我如何阅读 Card_0 而无需给 Card_0 的子项索引号,理论上我可以这样做,但必须有比这更好的方法吗?

Card_0 仅用作示例;我没有在代码中包含循环,因为在我可以读取 Card_# 的孩子之前,将它放入循环中是毫无意义的,例如。通过“Card_$i”获取卡片

?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root><DeckName>MelsDeckNoMedia</DeckName>
<NumberOfCards>42</NumberOfCards>
<Introduction>Some Text</Introduction>

<Card_0>
<Title>Title of Card</Title>
<Message></Message>
<Link>Name</Link>
<Timer>00:00:00</Timer>
<RollDice>false,</RollDice>
<CardImageURI>content://media/external/images/media/17233</CardImageURI>
<Math></Math>
<Questions></Questions>
<SkipPassword>false,</SkipPassword>
<AnimImageURI>content://media/external/images/media/17321</AnimImageURI>
<AnimImageAttributes>false,0,</AnimImageAttributes>
<FullScreenImageURI></FullScreenImageURI>
<FullScreenAttributes></FullScreenAttributes>
<VideoURI></VideoURI>
<VideoAttributes></VideoAttributes>
<AudioURI></AudioURI>
<AudioAttributes>0</AudioAttributes>
</Card_0>

<Card_1>
<Title></Title>
<Message></Message>
<Link></Link>
<Timer>00:00:00</Timer>
<RollDice>false,6</RollDice>
<CardImageURI>content://media/external/images/media/17233</CardImageURI>
<Math></Math>
<Questions></Questions>
<SkipPassword>false,</SkipPassword>
<AnimImageURI></AnimImageURI>
<AnimImageAttributes>false,0,</AnimImageAttributes>
<FullScreenImageURI></FullScreenImageURI>
<FullScreenAttributes></FullScreenAttributes>
<VideoURI></VideoURI>
<VideoAttributes></VideoAttributes>
<AudioURI></AudioURI>
<AudioAttributes>0</AudioAttributes>
</Card_1>

<Card_2>
<Title></Title>
<Message></Message>
<Link></Link>
<Timer>00:00:00</Timer>
<RollDice>true,6</RollDice>
<CardImageURI>content://media/external/images/media/17233</CardImageURI>
<Math></Math>
<Questions></Questions>
<SkipPassword>false,</SkipPassword>
<AnimImageURI></AnimImageURI>
<AnimImageAttributes>false,0,</AnimImageAttributes>
<FullScreenImageURI></FullScreenImageURI>
<FullScreenAttributes></FullScreenAttributes>
<VideoURI></VideoURI>
<VideoAttributes></VideoAttributes>
<AudioURI></AudioURI>
<AudioAttributes>0</AudioAttributes>
</Card_2>
</root>




//----------------------------------------------------------------------------------------------------
// XML get value by tag
//----------------------------------------------------------------------------------------------------
private fun readXMLTagValue( element: Element,tag : String ) : String {
    val nodeList = element.getElementsByTagName(tag).item(0).childNodes
    val node = nodeList.item(0)
    return node.nodeValue
}


//----------------------------------------------------------------------------------------------------
// Save Deck (Properties)
//----------------------------------------------------------------------------------------------------
fun loadDeckAsXML(appContext: Context,userpath : Uri,userfilename : String) {

    val file = File (userpath.toString(),userfilename)

    mytools.debug("loadDeckAsXML = ${userpath},${userfilename},output = $file")

    appContext.contentResolver.openInputStream(file.toUri()).use { inStream ->
        loadDeckFileXMLIO(appContext,inStream as FileInputStream)
    }

}

//----------------------------------------------------------------------------------------------------
// Load Deck File as XML
//----------------------------------------------------------------------------------------------------
private fun loadDeckFileXMLIO(appContext: Context, fis: FileInputStream) {

    try {
        val dbFactory = DocumentBuilderFactory.newInstance()
        val dBuilder = dbFactory.newDocumentBuilder()
        val doc = dBuilder.parse(fis)
        val element = doc.documentElement
        element.normalize()

        mydeckio.deckName = readXMLTagValue( element ,"DeckName" )
        mydeckio.deckNCards = readXMLTagValue( element ,"NumberOfCards" )
        mydeckio.deckIntroText = readXMLTagValue( element ,"Introduction" )

    } catch (e: FileNotFoundException) {
        Toast.makeText(appContext,"Deck file cannot be loaded", Toast.LENGTH_SHORT).show()
    } catch (e: IOException) {
        Toast.makeText(appContext,"IOEXCeption", Toast.LENGTH_SHORT).show()
    } finally {
        if (null != fis) {
            try {
                fis.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

【问题讨论】:

    标签: java android xml kotlin


    【解决方案1】:

    使用此代码

    private fun parseXml() {
        val stringBuilder = StringBuilder()
        
        //        1. Get document builder
        val documentBuilderFactory = DocumentBuilderFactory.newInstance()
        val documentBuilder = documentBuilderFactory.newDocumentBuilder()
    
        //        2. Get document
        val inputStream = assets.open("yourfile.xml")
        val document = documentBuilder.parse(inputStream)
    
        //        3. Normalize the xml structure
        document.documentElement.normalize()
    
        //        4. Get all element by tag name
        val usersNodeList = document.getElementsByTagName("root")
    
        for (userIndex in 0 until usersNodeList.length) {
    
            val userNode = usersNodeList.item(userIndex)
    
            if (userNode.nodeType == Node.ELEMENT_NODE) {
    
                val userElement = userNode as Element
    
                val userDataList = userElement.childNodes
    
                for (userDataIndex in 0 until userDataList.length) {
                    val userData = userDataList.item(userDataIndex)
                    if (userData.nodeType == Node.ELEMENT_NODE) {
                        val userDataElement = userData as Element
    
                        if (userDataElement.tagName.startsWith("Card")) {
    
                            stringBuilder.append(userDataElement.tagName + ": " + getValue(userDataElement) + "\n")
    
                            val newList = userDataElement.childNodes
    
                            for (newListIndex in 0 until newList.length) {
                                val newData = newList.item(newListIndex)
    
                                if (newData.nodeType == Node.ELEMENT_NODE) {
                                    val newUserDataElement = newData as Element
                                    if (newUserDataElement.childNodes.length == 0)
                                        stringBuilder.append(newUserDataElement.tagName + ": " + "NA" + "\n")
                                    else
                                        stringBuilder.append(newUserDataElement.tagName + ": " + getValue(newUserDataElement) + "\n")
    
                                }
                            }
                        } else
                            stringBuilder.append(userDataElement.tagName + ": " + getValue(userDataElement) + "\n")
                    }
                }
    
            }
        }
        Log.d("mydata", stringBuilder.toString())
    
    }
    
    
    private fun getValue(element: Element): String {
        val nodeList = element.childNodes
        val node = nodeList.item(0)
        return node.nodeValue
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 2019-02-03
      • 2021-03-07
      • 1970-01-01
      相关资源
      最近更新 更多