3

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.

4

3 回答 3

2

xpath 就是答案:)

        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);
于 2015-11-12T17:59:58.693 回答
1

使用String.Contains 方法检查字符串是否包含所需的子字符串,在这种情况下vId

public string GetID(string path)
{
    XmlReader reader = XmlReader.Create(path);
    while (reader.Read())
    {
        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "link"))
        {
        if (reader.HasAttributes)
        {
            var id = reader.GetAttribute("href");
            if (id.Contains(@"&vId"))
            {
                MessageBox.Show(id + "= correct id");
                return id;
            }
        }
    }
    return String.Empty;
}

如果可以接受,您也可以使用LINQ2XML

var reader = XDocument.Load(path); // or XDocument.Parse(path);
// take the outer link
Console.WriteLine(reader.Root.Element("link").Attribute("href").Value);

输出总是:

http://snow.traceup.com/stats/u?uId=397760&vId=1196854= first id

另一种选择是像@user5507337 建议的那样使用XPath。

于 2015-11-12T18:03:48.050 回答
0

XDocument 示例:

var xml = XDocument.Load(path); //assuming path points to file
var nodes = xml.Root.Elements("link");
foreach(var node in nodes)
{
    var href = node.Attribute("href").Value;
}
于 2015-11-12T18:17:37.027 回答