Patrik Daňo Patrik Daňo - 3 years ago 166
C# Question

XML read specific attribute

i'm tryin' to create a small application which allows its users to edit xml files.

I got XML file like this :

<item id="1" name="item_01">
<property name="Meshfile" value="path_to_mesh_file" />
<property name="Material" value="organic" />
<property name="HoldType" value="23" />
<property name="Stacknumber" value="50" /></property>
</item>
<item id="2" name="item_02">
<property name="Meshfile" value="path_to_mesh_file" />
<property name="Material" value="organic" />
<property name="HoldType" value="23" />
<property name="Stacknumber" value="50" /></property>
</item>
<item id="3" name="item_03">
<property name="Meshfile" value="path_to_mesh_file" />
<property name="Material" value="organic" />
<property name="HoldType" value="23" />
<property name="Stacknumber" value="50" /></property>
</item>
<item id="4" name="item_04">
<property name="Meshfile" value="path_to_mesh_file" />
<property name="Material" value="organic" />
<property name="HoldType" value="23" />
<property name="Stacknumber" value="50" /></property>
</item>


But i need to add into combobox every VALUE of Meshfiles , but im not sure how to.

Answer Source

Your xml posted has extra tag which must be removed. The xml posted is not well formed so I had to read as a fragment. See code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;

            XmlReader reader = XmlReader.Create(FILENAME, settings);

            List<string> meshFiles = new List<string>();
            while (!reader.EOF)
            {
                if (reader.Name != "property")
                {
                    reader.ReadToFollowing("property");
                }
                if (!reader.EOF)
                {
                    XElement property = (XElement)XElement.ReadFrom(reader);
                    if ((string)property.Attribute("name") == "Meshfile")
                    {
                        meshFiles.Add((string)property.Attribute("value"));
                    }
                }
            }
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download