使用xmldocument获取xml属性名称

时间:2012-10-22 17:34:39

标签: xml xmldocument xml-attribute

我正在使用C#,框架3.5。我正在使用xmldocument读取xml值。我可以获取属性的值,但我无法获取属性名称。 示例:我的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 个答案:

答案 0 :(得分:1)

XmlNode有一个Attributes集合。此集合中的项目为XmlAttributes。在Name中,XmlAttributes具有Valueothers个属性。

以下是循环遍历给定节点的属性并输出每个属性的名称和值的示例。

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

相关问题