【问题标题】:Confusion in xml attributes and attributes value comparisionxml属性和属性值比较的混淆
【发布时间】:2012-02-18 19:07:55
【问题描述】:

我对 XML 有一些困惑!我的 xml 文件如下所示

<rootnode>
<childnode id="1" quantity="3" type="auto">0000-000</childnode>
<childnode id="2" quantity="3" type="prop">1111-111</childnode>
<childnode id="2" quantity="3" type="toy">2222-222</childnode>
<childnode id="3" quantity="3" type="auto">0000-000</childnode>
</rootnode>

我正在创建一个函数,它将两个参数作为属性和属性值的数组。现在我有点困惑如何比较节点的每个属性?看看我的代码

 ComparableAttributes = new string[]{ "id","quantity"};

 ComparableAttributesValue = new string[]{ "2","3"};

根据我的要求,我必须有两个节点(第二个和第三个)。因为属性和属性值与该特定节点匹配!

  public List<XmlNode> getXmlNodeList()
    {
        XmlDocument Xdoc = new XmlDocument();
        Xdoc.Load(Filename);

        List<XmlNode> xmlList = new List<XmlNode>();

        foreach (XmlNode node in Xdoc.SelectNodes("//" + Childnode))
        {
            for (int i = 0; i < ComparableAttributes.Count() - 1; i++)
            {
                if (node.Attributes[ComparableAttributes[i]].Value == ComparableAttributesValue[i] &&
                    node.Attributes[ComparableAttributes[i + 1]].Value == ComparableAttributesValue[i + 1])
                    xmlList.Add(node);
            }
        }

        return xmlList;
    }

它只给我两个值的输出......!如果我想让它动态,那么我该如何迭代循环?我的意思是我怎么能提出条件!我只是有点困惑!

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    你几乎完全正确。还有一些小问题:

    for (int i = 0; i < ComparableAttributes.Count() - 1; i++)
    

    假设ComparableAttributes.Count()5。然后这个循环将给i0123 然后停止。但这省略了4!这里迭代的正确方法是

    for (int i = 0; i < ComparableAttributes.Count(); i++)
    

    for (int i = 0; i <= ComparableAttributes.Count() - 1; i++)
    

    下一个问题是,在 i 循环中,您正在测试 两个 索引,ii+1- 我怀疑您将其放入,因为在您的示例中您只打算循环一次。


    最后,也是最重要的一点,如果 any 的魔法属性是正确的,那么现在你正在接受一个节点,但听起来你只想接受一个节点,如果 all 的魔法属性是正确的。为此,我们需要引入一个新变量来跟踪节点是否良好,并确保检查我们需要的每个属性。

    我们最终得到的结果如下所示:

    foreach (XmlNode node in Xdoc.SelectNodes("//" + Childnode))
    {
        bool nodeIsGood = true;
    
        for (int i = 0; i < ComparableAttributes.Count(); i++)
        {
            if (node.Attributes[ComparableAttributes[i]].Value 
                             != ComparableAttributesValue[i])
            {
                // the attribute doesn't have the required value
                // so this node is no good
                nodeIsGood = false;
                // and there's no point checking any more attributes
                break;
            }
        }
    
        if (nodeIsGood)
            xmlList.Add(node);
    }
    

    试一试,看看它是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 2011-07-03
      • 2020-01-21
      • 2013-09-25
      • 1970-01-01
      相关资源
      最近更新 更多