Pregunta

This is probably quite noob, but I am having problems with something that is most lightly quite simple. This is my xml:

<CustomFieldOptions>
<DataType>Text</DataType>
<Options>
    <Option Key="Advokater">category_advokater</Option>
    <Option Key="Arkitektur- &amp; ingeniørvirksomheder">category_arkitektur</Option>
    <Option Key="Bank &amp; finans">category_bank</Option>
</Options>

I am trying to get the node value and the key attribute to a list, like:

using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            while(reader.Read())
            {
                reader.ReadToFollowing("Option");
                key = reader.ReadInnerXml();
                reader.MoveToFirstAttribute();
                value = reader.Value;

                if(key.Length > 0 && value.Length > 0)
                    categoryList.Add(key, value);
            }
        }

So, for the first Option I should get a Key-Value pair of <"category_advokater","Advokater">

But when adding to list I have mixed values of current/previous lines. Where am I getting wrong?

Thx in advance!

/snedker

¿Fue útil?

Solución 2

You can do that using LINQ to XML:

var xmlDocument = XDocument.Load("path");

var options = xmlDocument.Descendants("Option")
            .ToDictionary(x => (string)x, x => (string)x.Attribute("Key"));

Otros consejos

Reader is much faster and allow you to process the xml files partially.

Try this code snippet instead. ReadInnerXml advanced the read pointer to the next element. If you don't skip the next read in the while statement, you will end up skipping an element unintentionally.

using (XmlReader reader = XmlReader.Create(new StringReader(text))) {
bool skipRead = false;
while (skipRead || reader.Read()) {
    skipRead = false;
    if (reader.NodeType == XmlNodeType.Element && reader.Name == "Option") {
        string key = reader.GetAttribute("Key");
        string value = reader.ReadInnerXml();
        skipRead = true;
        Console.WriteLine("{0}.{1}", key, value);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top