使用libxml2解析XML

时间:2018-11-14 13:38:13

标签: c++ xml parsing libxml2

我几乎每天都在尝试使用libxml2 cpp库解析以下XML。我需要做两件事:

1)我需要在std :: vector数组中获取所有“ Bucket”标签的列表。

2)查找“ NextMarker”标签是否存在。

有两种可能的XML可以作为输入提供。

XML 1

<?xml version="1.0" encoding="utf-8"?>  
<EnumerationResults ServiceEndpoint="https://myaccount.blob.core.windows.net/">  
  <MaxResults>3</MaxResults>  
  <Containers>  
    <Bucket>  
      <Name>audio</Name>  
      <Properties>  
        <Last-Modified>Wed, 26 Oct 2016 20:39:39 GMT</Last-Modified>  
        <Etag>0x8CACB9BD7C6B1B2</Etag> 
        <PublicAccess>container</PublicAccess> 
      </Properties>  
    </Bucket>  
    <Bucket>  
      <Name>images</Name>  
      <Properties>  
        <Last-Modified>Wed, 26 Oct 2016 20:39:39 GMT</Last-Modified>  
        <Etag>0x8CACB9BD7C1EEEC</Etag>  
      </Properties>  
    </Bucket>  
    <Bucket>  
      <Name>textfiles</Name>  
      <Properties>  
        <Last-Modified>Wed, 26 Oct 2016 20:39:39 GMT</Last-Modified>  
        <Etag>0x8CACB9BD7BACAC3</Etag>  
      </Properties>  
    </Bucket>  
  </Containers>  
  <NextMarker>video</NextMarker>  
</EnumerationResults>

XML 2

<EnumerationResults>
    <Containers />
    <NextMarkerr>/pdtcava01a/container1</NextMarker>
</EnumerationReslts>

我的可怜代码:

int main(){
    // Read the file
    xmlDocPtr doc; /* the resulting document tree */
    doc = xmlReadFile("/home/cbs/hemant/azure_d_patch/backend_trim/file_xml.xml", NULL, 0);

    // Thing#2. Check if NextMarker tag is present. WORKING
    xmlNode *root = xmlDocGetRootElement(doc);
    xmlNodePtr lastChild = root->last->prev;
    xmlChar *NextMarker = xmlCharStrdup("NextMarker");
    if(!xmlStrcmp(lastChild->name, NextMarker)) {
        cout<<"NextMarker tag present"<<endl;
    }

    // thing#1. Failing to get the list of Buckets. NOT WORKING
    xmlChar *toFind = xmlCharStrdup("Containers");
    xmlNodePtr container = findNodeByName(root->children, toFind);
    container = container->children;

    XmlVal hem(container->children);
    std::vector<XmlVal> cont_list = hem.list(); // list() was my internal function which I now scraped.

    for (std::vector<XmlVal>::iterator it = cont_list.begin(); it != cont_list.end(); ++it) {
        bucket b;
        b.name_ = (*it)["Name"].content();
        b.creation_time_ = (*it)["Last-Modified"].content();
        cout<<b.name_<<"    "<<b.creation_time_<<endl;
        bucket_list.push_back(b);
    }
    return 1;

}

0 个答案:

没有答案