c# - xml属性与属性值比较的困惑

标签 c# xml

我对 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;
    }

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

最佳答案

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

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

假设 ComparableAttributes.Count()5。然后这个循环会给i0, 1, 2, 3然后停下来。但这省略了 4!这里迭代的正确方法是

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

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

下一个问题是,在 i 循环中,您正在测试 两个 索引,ii+1-我怀疑你把它放进去是因为在你的例子中你只循环了一次。


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

我们最终得到的结果是这样的:

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);
}

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

关于c# - xml属性与属性值比较的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005425/

相关文章:

c# - 为 ComboBox 中的项目分配非顺序索引

c# - PInvoke 的字符类型**

xml - Ant xmltask 添加一个空白 xmlns =""

ruby-on-rails - 如何使用 .xml.builder 文件从 XMLBuilder 生成 XML?

java - XML 生成后的 JAXB 日期时间格式

c# - 如何使用 Ruby/OpenSSL 解密/加密设置填充模式?

c# - 如何从列表 linq C# 的列表中获取列表 <string>

xml - INCLUDETEXT通过XPath选择特定的节点

xml - 创建一个可以导入到 EXCEL 的 XSD,具有基于元素值的限制

c# - WindowsPrincipal.IsInRole 和通用与全局事件目录组