使用 TBXML 解析子元素
我的 XML 如下所示:
<root>
<sets>
<childSets>
<childs>
<child>
<childId>11</childId>
</child>
<child>
<childId>22</childId>
</child>
<child>
<childId>33</childId>
</child>
<child>
<childId>44</childId>
</child>
[...]
</childs>
</childSets>
<childSets>
[...]
</childSets>
</sets>
</root>
我想解析 child
的所有 childId
元素。
实际上,我的解析结果只是每个 childs
元素的第一个 childId
:
[...]
do {
if ([[TBXML elementName:element] isEqualToString:@"childSet"]) {
[...]
TBXMLElement *xmlChildId = [TBXML childElementNamed:@"childId" parentElement:child];
[...]
}
} while ((element = element->nextSibling));
[...]
在本例中,我只得到 11
。这里出了什么问题?
编辑1:
解决方案是找到子元素的第一个子元素并解析其下一个元素,如下所示:
这段代码位于 traverseElement 方法的 do while 循环中
do { [...]
if ([[TBXML elementName:element] isEqualToString:@"childSet"]) {
//find the first child
if ((ChildPARENTELEMENT->firstChild)) {
while (ChildOfCHILDELEMENT!=nil) {
NSLog(@"....");
ChildOfCHILDELEMENT = [TBXML nextSiblingNamed:@"childs" searchFromElement:ChildOfCHILDELEMENT];
}
}
}
while((element = element->nextSibling));
My XML looks like this:
<root>
<sets>
<childSets>
<childs>
<child>
<childId>11</childId>
</child>
<child>
<childId>22</childId>
</child>
<child>
<childId>33</childId>
</child>
<child>
<childId>44</childId>
</child>
[...]
</childs>
</childSets>
<childSets>
[...]
</childSets>
</sets>
</root>
I want to pars all childId
elements of child
.
Actually, the result of my parsing is just the first childId
of every childs
element:
[...]
do {
if ([[TBXML elementName:element] isEqualToString:@"childSet"]) {
[...]
TBXMLElement *xmlChildId = [TBXML childElementNamed:@"childId" parentElement:child];
[...]
}
} while ((element = element->nextSibling));
[...]
In this case, I just get 11
. Whats wrong here?
EDIT 1:
The solution is to find the first child of the child element and to parse the next elements of this, here it is:
This code is in the do while loop of the method traverseElement
do { [...]
if ([[TBXML elementName:element] isEqualToString:@"childSet"]) {
//find the first child
if ((ChildPARENTELEMENT->firstChild)) {
while (ChildOfCHILDELEMENT!=nil) {
NSLog(@"....");
ChildOfCHILDELEMENT = [TBXML nextSiblingNamed:@"childs" searchFromElement:ChildOfCHILDELEMENT];
}
}
}
while((element = element->nextSibling));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案是找到子元素的第一个子元素并解析其下一个元素,如下所示:
这段代码位于 traverseElement 方法的 do while 循环中
The solution is to find the first child of the child element and to parse the next elements of this, here it is:
This code is in the do while loop of the method traverseElement
您需要一个遍历所有子 xml 元素的内部循环。
childElementName:parentElement:
将仅返回具有该名称的第一个子元素。尝试类似的方法:
You need an inner loop that goes through all the child xml elements. The
childElementName:parentElement:
will only return the first child with that name.Try something like: