**I am in process of reviewing the code as someone reported a potential bug, I have not verified this yet. I will make an update soon. Thanks for your patience -dec 19 - rj***
Our helper methods will create a dictionary of elements and dictionary of attributes. Therefore we simply loop through elements and attributes as so.
As always, with XML, there are 999 other ways to do the same thing however, this is simple syntax and a quick approach.
Dictionary<string, string> elements = GetElements( xmlFragment );
foreach ( var elementKeyPair in elements )
{
Dictionary<string, string> attributes = GetAttributes(elementKeyPair.Key, xmlFragment);
}
public static Dictionary<string, string> GetElements(string XmlFragment)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
byte[] byteArray = Encoding.ASCII.GetBytes(XmlFragment);
MemoryStream stream = new MemoryStream(byteArray);
XmlReader reader = XmlReader.Create(stream);
try
{
while (reader.Read())
{
if (reader.IsStartElement())
{
KeyValuePair<string, string> pair = new KeyValuePair<string, string>(reader.Name, reader.Value);
if (dictionary.Contains(pair) == false)
{
dictionary.Add(reader.Name, reader.Value);
}
}
}
}
catch { }
return dictionary;
}
public static Dictionary<string, string> GetAttributes(string element, string XmlFragement)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
byte[] byteArray = Encoding.ASCII.GetBytes(XmlFragement);
MemoryStream stream = new MemoryStream(byteArray);
XmlReader reader = XmlReader.Create(stream);
while (reader.Read())
{
if (reader.IsStartElement())
{
if ( reader.Name == element )
{
for ( int i = 0; i < reader.AttributeCount; ++i )
{
reader.MoveToNextAttribute();
dictionary.Add(reader.Name, reader.Value);
}
}
}
}
return dictionary;
}