0

我正在使用 LibXML。我使用 xml 文件:

<all>
<material name1= "AS4C" name2="IPS06"/>
    <associated name1="IMA_1" name2="IPS05"/>
    <associated name1="IMA_2" name2="IPS05"/>
    <associated name1="IMA_3" name2="IPS05"/>
    <associated name1="AS4C" name2="IPS05"/>
    <associated name1="AS3C" name2="IPS05"/>
<material />

<material name1="IMA_1" name2="IPS06"/>
    <associated name1="IMA_1" name2="IPS05"/>
    <associated name1="AS4C" name2="IPS05"/>
    <associated name1="HTA_M" name2="IPS05"/>
    <associated name1="IMA_M21E" name2="IPS05"/>
<material />
</all>

我正在尝试检查例如关联的 name1="IMA_3" name2="IPS05"/ 是否存在于材料 name1= "AS4C" name2="IPS06"/中。但是结果是空的(xmlXPathNodeSetIsEmpty(result->nodesetval) 我认为路径不正确。

string s_mat1 = "AS4C";
string s_spec1 = "IPS06";
string s_mat2 = "IMA_3";
string s_spec2 = "IPS05";
sPath <<  "/all/material[@name1=\"" << s_mat1 << "\"][@name2=\"" << s_spec1 << "\"]/associated[@name1=\"" << s_mat2 << "\"][@name2=\"" << s_spec2 << "\"]";
result = xmlXPathEvalExpression((xmlChar *) sPath.str().c_str(), ctxt);
if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
    cout << "empty" << endl;
}
if (result->type == XPATH_NODESET) {

        xmlNodePtr matNode = result->nodesetval->nodeTab[0];
        xmlChar *matNode2 = xmlNodeGetContent(matNode);

        struct _xmlAttr* matAttr = matNode->properties;

        while (matAttr) {
            cout << "matAttr :" << string((char *)matAttr->name) << endl;
            if (string((char *)matAttr->name)=="name1" && matAttr->children){
                string name1= string((char *)matAttr->children->content);
                cout << "___ name1==" << name1<< endl;

                xmlChar* value = xmlNodeListGetString(matNode->doc, matAttr->children, 1);
                cout << "value ==" << string((char *)value)  << endl;

            }
            else if (string((char *)matAttr->name)=="name2"){
                string name2= string((char *)matAttr->children->content);
                cout << "___ name2==" << name2<< endl;
            }
            matAttr = matAttr->next;
        }
}

谢谢。

4

1 回答 1

0

不确定是否不是另一个错字(但会更不寻常),但您的 xml 数据不适合您的查询。我猜你的 xml 文件不是你真正想要的,而是应该是:

<material name1= "AS4C" name2="IPS06">
    <associated name1="IMA_1" name2="IPS05"/>
    <associated name1="IMA_2" name2="IPS05"/>
    <associated name1="IMA_3" name2="IPS05"/>
    <associated name1="AS4C" name2="IPS05"/>
    <associated name1="AS3C" name2="IPS05"/>
</material>

<material name1="IMA_1" name2="IPS06">
    <associated name1="IMA_1" name2="IPS05"/>
    <associated name1="AS4C" name2="IPS05"/>
    <associated name1="HTA_M" name2="IPS05"/>
    <associated name1="IMA_M21E" name2="IPS05"/>
</material>
</all>;

请注意,在您的示例中,materialandassociated节点是兄弟姐妹,但现在associatedmaterial.

于 2012-11-08T09:57:12.743 回答