gpt4 book ai didi

Java Android : XML Parsing getting the value of a tag

转载 作者:行者123 更新时间:2023-12-01 16:34:50 25 4
gpt4 key购买 nike

我正在尝试解析 xml 文件,但似乎不明白它是如何工作的。我已经调试了几个小时,但似乎无法获得正确的值。我已经设法让代码适用于 tracklist 标签,但不适用于playbacklist 标签及其子标签。

我想要一个播放设备的值,将来会添加更多。

这是 xml 源:

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<tracklist>
<track>track001.mp3</track>
<track>track002.mp3</track>
<track>track003.mp3</track>
<track>track004.mp3</track>
<track>track005.mp3</track>
<track>track006.mp3</track>
<track>track007.mp3</track>
<track>track008.mp3</track>
<track>track009.mp3</track>
<track>track010.mp3</track>
</tracklist>
<playbacklist>
<playback>
<name>Speaker1</name>
<ip>192.168.1.103</ip>
<room>Kitchen</room>
<options>0</options>
<state>NotPlaying</state>
</playback>
</playbacklist>
</root>

这是java代码(代码 fragment ):这个代码对我有用

DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(inStream);
NodeList nodeList = doc.getElementsByTagName("root");

for (int index = 0; index < nodeList.getLength(); index++) {
Node node = nodeList.item(index);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList nameNode = element.getChildNodes();
for (int iIndex = 0; iIndex < nameNode.getLength(); iIndex++) {
if (nameNode.item(iIndex).getNodeType() == Node.ELEMENT_NODE) {
Element nameElement = (Element) nameNode.item(iIndex);
if(nameElement.getNodeName().equals("tracklist")){
NodeList trackNodes = nameElement.getChildNodes();
for(int i=0;i<trackNodes.getLength();i++){
if (trackNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element trackElement = (Element) trackNodes.item(i);
playlist.add(trackElement.getFirstChild().getNodeValue());
}
}
}

此代码对我不起作用:

        if(nameElement.getNodeName().equals("playbacklist")){
NodeList devicesNodes = nameElement.getChildNodes();
for(int j=0;j<=devicesNodes.getLength();j++){
Node nodeDevice = devicesNodes.item(j);
NodeList childNodes = nodeDevice.getChildNodes();

最佳答案

我建议你使用SAX解析器,它比其他解析器简单且高效

如何解析:How to parse XML using the SAX parser

关于Java Android : XML Parsing getting the value of a tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com