Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# xml reader, same element name

Tags:

c#

xml

reader

I'm trying to read an element from my xml file. I need to read an string in an "link" element inside the "metadata", but there are 2 elements called "link", I only need the second one:

<metadata>
<name>visit-2015-02-18.gpx</name>
<desc>February 18, 2015. Corn</desc>
<author>
    <name>text</name>
    <link href="http://snow.traceup.com/me?id=397760"/>
</author>
<link href="http://snow.traceup.com/stats/u?uId=397760&amp;vId=1196854"/>
<keywords>Trace, text</keywords>

I need to read this line:

<link href="http://snow.traceup.com/stats/u?uId=397760&amp;vId=1196854"/>

This is the working code for the first "link" tag, it works fine,

        public string GetID(string path)
    {
        string id = "";
        XmlReader reader = XmlReader.Create(path);
        while (reader.Read())
        {
            if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "link"))
            {
                    if (reader.HasAttributes)
                    {
                        id = reader.GetAttribute("href");
                        MessageBox.Show(id + "= first id");
                        return id;
                        //id = reader.ReadElementContentAsString();
                    }
                }
            }
            return id;
        }

Does anyone know how I can skip the first "link" element? or check if reader.ReadElementContentAsString() contains "Vid" or something like that?

I hope you can help me.

like image 622
washichi Avatar asked Aug 25 '26 05:08

washichi


1 Answers

xpath is the answer :)

        XmlReader reader = XmlReader.Create(path);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        XmlNodeList nodes = doc.SelectNodes("metadata/link");
        foreach(XmlNode node in nodes)
             Console.WriteLine(node.Attributes["href"].Value);
like image 110
owairc Avatar answered Aug 26 '26 18:08

owairc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!