2009-01-06 182 views
5

我正在接受動態xml,我不知道屬性名稱,如果你看看xml和代碼......我試圖做一個簡單的例子,我可以獲得屬性值,即「myName」,「myNextAttribute」和「blah」,但我無法獲得屬性名稱,即「name」,「nextAttribute」和「etc1」。任何想法,我認爲它必須是我很想念的東西......但我肯定錯過了它。獲取屬性名稱除了xml中的屬性值

static void Main(string[] args) 
    { 
     string xml = "<test name=\"myName\" nextAttribute=\"myNextAttribute\" etc1=\"blah\"/>"; 

     TextReader sr = new StringReader(xml); 

     using (XmlReader xr = XmlReader.Create(sr)) 
     { 
      while (xr.Read()) 
      { 
       switch (xr.NodeType) 
       { 
        case XmlNodeType.Element: 
         if (xr.HasAttributes) 
         { 
          for (int i = 0; i < xr.AttributeCount; i++) 
          { 
           System.Windows.Forms.MessageBox.Show(xr.GetAttribute(i)); 
          } 
         } 
         break; 
        default: 
         break; 
       } 
      } 
     } 
    } 

回答

23

你可以看到MSDN

if (reader.HasAttributes) { 
    Console.WriteLine("Attributes of <" + reader.Name + ">"); 
    while (reader.MoveToNextAttribute()) { 
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value); 
    } 
    // Move the reader back to the element node. 
    reader.MoveToElement(); 
} 
+0

謝謝,我認爲它必須是密切的...我也在我原來的循環中找到了,我可以完成xr.MoveToAttribute(i)並獲得相同的效果。 – 2009-01-06 16:00:49

0

你的開關是不必要的,因爲你只有一個單一的情況下,試圖滾動到這一點你如果語句。

if (xr.NodeType && xr.HasAttributes) 
{ 
    ... 
} 

注意,& &運營商在評估順序,因此如果xr.NoteType是假的,對剩餘參數被忽略,如果塊被跳過。

+0

在這個例子中,是的,我在'真實世界'場景中有更多案例,我只是試圖保持清潔。不過謝謝。 – 2009-01-06 16:01:47