1

我正在使用 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;
}

如何获取属性名称 (name,Age) 而不是它们的值。谢谢

4

1 回答 1

1

XmlNode有一个Attributes集合。此集合中的项目是XmlAttributes。XmlAttributes 具有NameValue属性

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

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

于 2012-10-22T17:38:41.570 回答