【问题标题】:tinyxml parsing xml filetinyxml 解析 xml 文件
【发布时间】:2014-12-17 21:57:58
【问题描述】:

我有一个这样的 xml 文件:

<?xml version="1.0"?>

<ApplicationSettings>
    <BeamGeometry  
        Dimension="2"
        Type="fan"
        Shape="arc"
        LengthFocalPointToISOCenter="558"
        LengthISOCenterToDetector="394"
        LengthDetectorSeperation="0.98"
        LengthModuleSeperation="0.04"
        NumberModules="57" 
        NumberDetectorsPerModule="16" 
        NumberISOCenterShift="3.25" />
</ApplicationSettings>

我想使用 tinyxml 根据条目名称(例如 (LengthFocalPointToISOCenter))检索所有值(例如 558)。这是我的代码,还没有成功。

int SetFanbeamGeometry(const char* filename)    
{   
    int ret = TRUE;

    TiXmlDocument doc("E:\\Projects\\iterativeRecon\\ProjectPackage\\ApplicationSettings\\ApplicationSettings.xml");

    int LengthFocalPointToISOCenter;

    if( doc.LoadFile())
    {

        TiXmlHandle hDoc(&doc);
        TiXmlElement *pRoot, *pParm;
        pRoot = doc.FirstChildElement("ApplicationSettings");
        if(pRoot)
        {
            pParm = pRoot->FirstChildElement("BeamGeometry");
            int i = 0; // for sorting the entries
            while(pParm)
            {
                pParm = pParm->NextSiblingElement("BeamGeometry");
                i++;
            }
        }
    }
    else
    {
        printf("Warning: ApplicationSettings is not loaded!");
        ret = FALSE;
    }

    return ret;
}

我想知道如何使用 tinyxml 来做到这一点?对不起,我是第一次使用。我看起来很困惑。谢谢。

【问题讨论】:

    标签: c++ xml tinyxml


    【解决方案1】:

    您显示的 sn-p 中只有一个 BeamGeometry 子元素;您尝试访问的信息是它的属性 - 它们不是单独的元素。

    所以你需要这样的东西:

    // ...
    pParm = pRoot->FirstChildElement("BeamGeometry");
    if (pParm)
    {
        const char* pAttr = pParm->Attribute("LengthFocalPointToISOCenter");
        if (pAttr)
        {
            int iLengthFocalPointToISOCenter = strtoul(pAttr, NULL, 10);
            // do something with the value
        }
    }
    

    如果要循环遍历所有属性,很简单:

    const TiXmlAttribute* pAttr = pParm->FirstAttribute();
    while (pAttr)
    {
        const char* name = pAttr->Name(); // attribute name
        const char* value = pAttr->Value(); // attribute value
        // do something
        pAttr = pAttr->Next();
    }
    

    【讨论】:

    • 谢谢。但是如果我想遍历所有条目呢?
    • @Ono:将其添加到答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多