2012-10-22 69 views
1

我正在使用C#,框架3.5。我正在使用xmldocument讀取xml值。我可以獲取屬性的值,但我無法獲取屬性名稱。 例子:我的XML看起來像使用xmldocument得到xml屬性名稱

<customer> 
<customerlist name = AAA Age = 23 /> 
<customerlist name = BBB Age = 24 /> 
</customer> 

我可以使用下面的代碼讀取值:

foreach(xmlnode node in xmlnodelist) 
{ 
    customerName = node.attributes.getnameditem("name").value; 
    customerAge = node.attributes.getnameditem("Age").value; 
} 

如何獲得屬性的名稱,而不是它們的值(姓名,年齡)。謝謝

回答

1

一個XmlNode有一個Attributes集合。這個集合中的物品是XmlAttributes。 XmlAttributes有NameValue屬性,其中others

以下是循環給定節點的屬性並輸出每個屬性的名稱和值的示例。

XmlNode node = GetNode(); 

foreach(XmlAttribute attribute in node.Attributes) 
{ 
    Console.WriteLine(
     "Name: {0}, Value: {1}.", 
     attribute.Name, 
     attribute.Value); 
} 

當心,從文檔的XmlNode.Attributes

如果節點是類型XmlNodeType.Element的,被返回的節點 的屬性。否則,該屬性返回null。

更新

如果你知道,恰好有兩個屬性,而您想要在同一時間他們的名字,你可以這樣做以下:

string attributeOne = node.Attributes[0].Name; 
string attributeTwo = node.Attributes[1].Name; 

請參閱http://msdn.microsoft.com/en-us/library/0ftsfa87.aspx

+0

查看更新。 –

+0

感謝您的回覆。所以我想讀取元素的屬性名稱,如if(1stAttribute.name ==「Name」和2ndAttribute.Name =「Age」),然後做一些事情。所以我需要根據屬性名稱自定義代碼。那麼如何獲取與該元素關聯的所有屬性名稱。 –

+0

謝謝seth。是的,現在它將是2個屬性,但我不知道如果我想要它更通用,必須做些什麼。 –