XML到字符串(C#)

本文关键字:字符串 XML | 更新日期: 2023-09-27 18:21:19

我有一个从如下URL加载的XML:

WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
try
{
    string reply = client.DownloadString("http://Example.com/somefile.xml");
    label1.Text = reply;
}
catch
{
    label1.Text = "FAILED";
}

该XML属于RSS提要。我想要那个标签1。文本只显示那个XML的标题。我怎样才能做到这一点?

标签示例1.文本

This is my first title    -    This is my 2nd title    -    And this is my last title

XML到字符串(C#)

您可以将XML加载到XmlDocument中,然后使用XPath获取目标节点的值。

       XmlDocument doc = new XmlDocument();
       doc.LoadXml(reply);
       XmlNodeList nodes = doc.SelectNodes("//NodeToSelect");
       foreach (XmlNode node in nodes)
       {
           //If the value you want is the content of the node
           label1.Text = node.InnerText; 
           //If the value you want is an attribute of the node
           label1.Text = node.Attributes["AttibuteName"].Value; 
       }

如果您不熟悉XPath,可以随时查看此处:http://www.w3schools.com/xpath/xpath_syntax.asp

var xml= XElement.Parse(reply);
label1.Text = string.Join(Environment.NewLine, xml
.Descendants()
.Where (x => !string.IsNullOrEmpty(x.Value))
.Select(x=> string.Format("{0}: {1}", x.Name, x.Value))
.ToArray());

您可能需要手动解析RSSXML才能获得标题。以下是一些示例代码供您参考:

private static List<FeedsItem> ParseFeeds(string feedsXml)
{
    XDocument xDoc = XDocument.Parse(feedsXml);
    XNamespace xmlns = "http://www.w3.org/2005/Atom";
    var items = from entry in xDoc.Descendants(xmlns + "entry")
                select new FeedsItem
                {
                    Id = (string)entry.Element(xmlns + "id").Value,
                    Title = (string)entry.Element(xmlns + "title").Value,
                    AlternateLink = (string)entry.Descendants(xmlns + "link").Where(link => link.Attribute("rel").Value == "alternate").First().Attribute("href").Value
                };
    Console.WriteLine("Count = {0}", items.Count());
    foreach(var i in items)
    {
        Console.WriteLine(i);
    }
    return null;
}