如何使用Xerces c ++在有多个相同名称时仅解析1个标记

时间:2016-11-02 23:43:08

标签: c++ xml parsing xerces

我正在尝试解析xml文件,我找到了正确的标题标签但是有多个标题标签,我需要解析第一个标题标签。目前,我的代码输出所有标题标签 例如:

<book>
   <title>
   <title>
   <title>
<book>
<movie>
   <title>
<movie>

我只需要书中的第一个标题。

我当前的代码会提取书中的所有标题标签并输出它们。有没有办法在第一个冠军后停止?感谢。

void MySaxHandler::startElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attrs
) {
char* message = XMLString::transcode(localname);
if (strcmp(message, "book") == 0) {
    book = true;
}
else if (book && strcmp(message, "title") == 0) {
    title = true;
    titleBuffer = "";
}
else if (strcmp(message, "movie") == 0) {
    book = false;
}
else if (book && strcmp(message, "name") == 0) {
    title = false;
}
XMLString::release(&message);

1 个答案:

答案 0 :(得分:0)

title标记设为size_t并将其初始化为size_t(-1)

然后将if (book && strcmp(message, "title") == 0)更改为:

else if (book && strcmp(message, "title") == 0 ) {
    title++;
    if(0 == title) { // this is the one we want
      titleBuffer = "";
      // perhaps registering a callback with the parser - say, firstTitleFound
      // would allow you to do something like
      // firstTitleFound(titleBuffer);
      // and then capture the first titles of all the books in your document
    }
}

每当遇到任何可能包含标题的元素时,也许还会将标题重置为size_t(-1)