C# , xml parsing. get data between tags

use*_*412 2 c# xml

I have a string :

responsestring = "<?xml version="1.0" encoding="utf-8"?>
<upload><image><name></name><hash>SOmetext</hash>"
Run Code Online (Sandbox Code Playgroud)

How can i get the value between

<hash> and </hash>
Run Code Online (Sandbox Code Playgroud)

?

My attempts :

responseString.Substring(responseString.LastIndexOf("<hash>") + 6, 8); // this sort of works , but won't work in every situation.
Run Code Online (Sandbox Code Playgroud)

also tried messing around with xmlreader , but couldn't find the solution.

ty

Vin*_*B R 8

尝试

XDocument doc = XDocument.Parse(str);
var a = from hash in doc.Descendants("hash")
        select hash.Value;
Run Code Online (Sandbox Code Playgroud)

您将需要System.Core和System.Xml.Linq程序集引用


Jon*_*eet 7

其他人建议使用LINQ to XML解决方案,如果可能的话,我也会使用它.

如果您坚持使用.NET 2.0,请使用XmlDocument甚至是XmlReader.

但是不要试图使用Substring和自己操纵原始字符串IndexOf.使用某些描述的XML API .否则你错的.这是使用正确的工具来完成工作的问题.正确解析XML是一项重要的工作 - 已经完成的工作.

现在,只是为了使这个完整答案,这是一个使用您的示例数据的简短但完整的程序:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string response = @"<?xml version='1.0' encoding='utf-8'?>
<upload><image><name></name><hash>Some text</hash></image></upload>";

        XDocument doc = XDocument.Parse(response);

        foreach (XElement hashElement in doc.Descendants("hash"))
        {
            string hashValue = (string) hashElement;
            Console.WriteLine(hashValue);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,这将遍历所有hash元素.如果您只想要一个,您可以使用doc.Descendants("hash").Single()doc.Descendants("hash").First()根据您的要求.

请注意,我在此处使用的转换和Value属性都将返回元素中所有文本节点的串联.希望你没问题 - 或者你可以在必要时获得第一个直接子节点的文本节点.