Iterate over unkown attributes

  • Thread starter Thread starter barnum
  • Start date Start date
B

barnum

Hi,

I have an XML doc with a node with several unknown attributes, e.g.
<Fruit banana="true" apple="false" lemon="true" />

Is there a .NET-method to iterate over the attributes without knowing
their names?
(XPathNavigator.GetAttribute requires that I know what attribute to
look for.)

Thanks!
 
Hi,

I have an XML doc with a node with several unknown attributes, e.g.
<Fruit banana="true" apple="false" lemon="true" />

Is there a .NET-method to iterate over the attributes without knowing
their names?
(XPathNavigator.GetAttribute requires that I know what attribute to
look for.)

If you are using XPathNavigator then you can simply use .Select("@*") when
on the Fruit element.
 
I have an XML doc with a node with several unknown attributes, e.g.
<Fruit banana="true" apple="false" lemon="true" />

Is there a .NET-method to iterate over the attributes without knowing
their names?
(XPathNavigator.GetAttribute requires that I know what attribute to
look for.)

XPathDocument doc = new XPathDocument(new
StringReader(@"<Fruit banana=""true"" apple=""false"" lemon=""true"" />"));

foreach (XPathNavigator att in
doc.CreateNavigator().Select("Fruit/@*"))
{
Console.WriteLine("Attribute with name \"{0}\" has
value \"{1}\".", att.Name, att.Value);
}
 
Is there a .NET-method to iterate over the attributes without knowing
their names?

As an alternative to the earlier suggestion:

XPathDocument doc = new XPathDocument(new
StringReader(@"<Fruit banana=""true"" apple=""false"" lemon=""true"" />"));

XPathNavigator root =
doc.CreateNavigator().SelectSingleNode("Fruit");
if (root.MoveToFirstAttribute())
{
do
{
Console.WriteLine("Attribute with name \"{0}\" has
value \"{1}\".", root.Name, root.Value);
}
while (root.MoveToNextAttribute());
}
 
Back
Top