2012-01-25 54 views
3

我有一些什麼混淆的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> 

我的XML文件中給出我創建一個函數有兩個參數,屬性和attributevalues的陣列。現在我有點混淆瞭如何比較節點的每個屬性和每個屬性?看一下我的代碼

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

它給我輸出只有兩個值...!如果我想使它動態,那麼我如何迭代循環?我的意思是我怎麼能忍受這個狀況!我只是有點困惑!

回答

1

你幾乎完全正確。還有一些小問題:

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

假設ComparableAttributes.Count()5。然後這個循環將給出i的值0,1,2,3然後停止。但是這是省略4!在這裏重複正確的方法是要麼

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

OR

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

給一個去,看看它是否工作。

+0

It Works!謝謝 ! – Chintan