3

我希望仅在节点中具有值的情况下打印出客户的选项。我可以访问信息并将其打印出来,但是,由于 while 循环,它会打印出每个帐户下的信息。任何帮助或提示将不胜感激,谢谢。

这是访问xml的代码:

XPathNodeIterator ItemOptionsIter;
String ItemsearchStringOptions = "Order/Items/Item/CustomerOptions";
ItemOptionsIter = nav.Select(ItemsearchStringOptions);

if (ItemIter.Current.SelectSingleNode("CustomerOptions") != null)
{
    while (ItemOptionsIter.MoveNext())
    {
        XPathNodeIterator ItemOptions = ItemOptionsIter.Current.SelectChildren(XPathNodeType.Element);
        if (ItemOptions.Current.HasChildren)
        {
            txtItemInfo.Text = txtItemInfo.Text + "Size: " + ItemOptions.Current.SelectSingleNode("Size") + Environment.NewLine;
            txtItemInfo.Text = txtItemInfo.Text + "Color: " + ItemOptions.Current.SelectSingleNode("Color") + Environment.NewLine;
            txtItemInfo.Text = txtItemInfo.Text + "-------------------------------------------------" + Environment.NewLine;
        }
    }
}

这是xml文件:

<Item>
    <PartNo>JETSWEATER</PartNo>
    <Description>N.Y. Jets Sweatshirt</Description>
    <UnitPrice>10.50</UnitPrice>
    <Quantity>2</Quantity>
    <TotalCost>21.00</TotalCost>
    <CustomerOptions>
        <Size>M</Size>
        <Color>Green</Color>
    </CustomerOptions>
</Item>
<Item>
    <PartNo>JETSSWEATER</PartNo>
    <Description>N.Y. Jets Sweatshirt</Description>
    <UnitPrice>7.50</UnitPrice>
    <Quantity>3</Quantity>
    <TotalCost>22.50</TotalCost>
    <CustomerOptions>
        <Size>S</Size>
        <Color>White</Color>
    </CustomerOptions>
</Item>
<Item>
    <PartNo>JETSFLAG</PartNo>
    <Description>N.Y. Jets Flag for display</Description>
    <UnitPrice>5.00</UnitPrice>
    <Quantity>1</Quantity>
    <TotalCost>5.00</TotalCost>
    <CustomerOptions/>
</Item>

最后是我的输出示例:

零件编号:喷气式针织衫
描述:NY Jets 运动衫
单价:10.50
数量:2
总成本:21.00
-------------------------------------------------
尺码:M
颜色:绿色
-------------------------------------------------
尺寸:S
白颜色
-------------------------------------------------
零件编号:喷气式针织衫
描述:NY Jets 运动衫
单价:7.50
数量:3
总成本:22.50
-------------------------------------------------
尺码:M
颜色:绿色
-------------------------------------------------
尺寸:S
白颜色
-------------------------------------------------
零件编号:JETSFLAG
描述:用于展示的纽约喷气机队旗帜
单价:5.00
数量:1
总成本:5.00
-------------------------------------------------
尺码:M
颜色:绿色
-------------------------------------------------
尺寸:S
白颜色
-------------------------------------------------
4

1 回答 1

0

我会说构建您的主循环以遍历 Item 节点并打印出它们的值,然后在您将打印出选项的地方执行以下操作:

XPathNodeIterator options = item.SelectNodes("CustomerOptions/*[. != '']");
if(options.Count != 0)
{
  XPathNavigator size = item.SelectSingleNode("CustomerOptions/Size[. != '']");
  if(size != null)
  {
    txtItemInfo.Text = txtItemInfo.Text + "Size: " + size.Value + Environment.NewLine;            
  }
  // Then do the same for color

  txtItemInfo.Text = txtItemInfo.Text + "-------------------------------------------------" + Environment.NewLine;
}
于 2013-01-09T03:02:37.587 回答