如何在迭代循环中找到同一节点中的多个子元素

时间:2014-09-14 14:03:31

标签: c++ xml xpathnavigator

我在xml数据文件下面,其中两个节点的数量超过100,

<DO>
   <delivery>
    <dono>DM202422</dono>
    <custcode>M15</custcode>
    <custname>A Company</custname>
    <stockcode>ZPP56012303001</stockcode>
    <stockdesc>56012303001 DUPLEX PTD BOX</stockdesc>
    <unitprice>2.1900</unitprice>
    <qty>500</qty>
    <amount>1095.00</amount>
  </delivery>
  <delivery>
    <dono>DM202432</dono>
    <custcode>M23</custcode>
    <custname>B Company</custname>
    <stockcode>ZPP5605855V16</stockcode>
    <stockdesc>5605855 V16 PLAIN BOX</stockdesc>
    <unitprice>0.1000</unitprice>
    <qty>2000</qty>
    <amount>200.00</amount>
  </delivery>
</DO>

我的问题是假设我可以使用XPathNavigator在每个节点下显示2个子元素值。

如果让我说我需要在每行迭代循环中显示dono和custcode,例如dono =&#34; DM202422&#34;和custcode =&#34; M15&#34;在custname =&#34; A Company&#34;。

任何人都可以帮助我改进我的下面的代码,它只是在我对下一个子元素之后显示一个子元素和相同的元素。

void queryinxpath()
{

    System::Xml::XPath::XPathDocument^ doc = gcnew System::Xml::XPath::XPathDocument("C:/test.xml");

    System::Xml::XPath::XPathNavigator^ nav = doc->CreateNavigator();

    System::Xml::XPath::XPathExpression^ expr = nav->Compile("descendant::delivery[amount > 100]");

    System::Xml::XPath::XPathNodeIterator^ iterator=nav->Select(expr);

    while (iterator->MoveNext())
    {
        System::Xml::XPath::XPathNavigator^ nav_ = iterator->Current->Clone();

        nav_->MoveToChild("dono","");

        System::Console::WriteLine("DO No: {0} ",nav_->Value);

        nav_->MoveToChild("custcode","");

        System::Console::WriteLine("Customer Code : {0} ",nav_->Value);

        System::Console::WriteLine("\n");

    }


}

错误结果的结果:

DO No:DM202422

客户代码:DM202422

我想要的结果:

DO No:DM202422

客户代码:M15

提前感谢任何人都可以解决我的问题。

1 个答案:

答案 0 :(得分:0)

将nav _-&gt; MoveToParent()添加到nav的顶部_-&gt;每个占用的导航器后,MoveToChild(“dono”,“”)将解决我的问题。

while (iterator->MoveNext())
    {
        System::Xml::XPath::XPathNavigator^ nav_ = iterator->Current->Clone();

        nav_->MoveToChild("dono","");

        System::Console::WriteLine("DO No: {0} ",nav_->Value);

        nav_->MoveToParent();
        nav_->MoveToChild("custcode","");

        System::Console::WriteLine("Customer Code : {0} ",nav_->Value);

        nav_->MoveToParent();
        nav_->MoveToChild("custname","");

        System::Console::WriteLine("Customer Name : {0} ",nav_->Value);

        System::Console::WriteLine("\n");

    }