获取xml节点的文本

时间:2016-03-31 10:06:46

标签: c# xml nodes

示例XML:

<query yahoo:count="1" yahoo:created="2016-03-31T06:43:49Z" yahoo:lang="en-US">
    <results>
        <channel>
            <item>
                <yweather:condition code="28" date="Thu, 31 Mar 2016 08:00 AM SAST" temp="58" text="Mostly Cloudy"/>
            </item>
        </channel>
    </results>
 </query>

代码:

string weburl = "https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20%28select%20woeid%20from%20geo.places%281%29%20where%20text%3D%22Cape%20Town%22%29&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

var xml = await new WebClient().DownloadStringTaskAsync(new Uri(weburl));

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlElement root = doc.DocumentElement;

XmlNodeList nodes = root.SelectNodes("//query/results/channel/item");

foreach (XmlNode node in nodes)
{
    MessageBox.Show(node.InnerXml);
}

我一直在努力让 temp 文字输出,但我无法找到方法,这是我所得到的。< / p>

3 个答案:

答案 0 :(得分:0)

您可以从XmlNode.Attributes属性访问XML属性:

var condition = doc.SelectSingleNode("/query/results/channel/item/*");
MessageBox.Show(condition.Attributes["text"].Value);
MessageBox.Show(condition.Attributes["temp"].Value);

答案 1 :(得分:0)

试试这个......

... Usings

using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

类....

    [XmlRoot(ElementName = "condition", Namespace = "http://xml.weather.yahoo.com/ns/rss/1.0")]
    public class Condition
    {
        [XmlAttribute(AttributeName = "yweather", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Yweather { get; set; }
        [XmlAttribute(AttributeName = "code")]
        public string Code { get; set; }
        [XmlAttribute(AttributeName = "date")]
        public string Date { get; set; }
        [XmlAttribute(AttributeName = "temp")]
        public string Temp { get; set; }
        [XmlAttribute(AttributeName = "text")]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName = "item")]
    public class Item
    {
        [XmlElement(ElementName = "condition", Namespace = "http://xml.weather.yahoo.com/ns/rss/1.0")]
        public Condition Condition { get; set; }
    }

    [XmlRoot(ElementName = "channel")]
    public class Channel
    {
        [XmlElement(ElementName = "item")]
        public Item Item { get; set; }
    }

    [XmlRoot(ElementName = "results")]
    public class Results
    {
        [XmlElement(ElementName = "channel")]
        public Channel Channel { get; set; }
    }

    [XmlRoot(ElementName = "query")]
    public class Query
    {
        [XmlElement(ElementName = "results")]
        public Results Results { get; set; }
        [XmlAttribute(AttributeName = "yahoo", Namespace = "http://www.w3.org/2000/xmlns/")]
        public string Yahoo { get; set; }
        [XmlAttribute(AttributeName = "count", Namespace = "http://www.yahooapis.com/v1/base.rng")]
        public string Count { get; set; }
        [XmlAttribute(AttributeName = "created", Namespace = "http://www.yahooapis.com/v1/base.rng")]
        public string Created { get; set; }
        [XmlAttribute(AttributeName = "lang", Namespace = "http://www.yahooapis.com/v1/base.rng")]
        public string Lang { get; set; }
    }

...代码

        XmlDocument xmlDocument = new XmlDocument();
        try
        {
            xmlDocument.Load("https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20%28select%20woeid%20from%20geo.places%281%29%20where%20text%3D%22Cape%20Town%22%29&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");

            string XMLxmlDocument = xmlDocument.InnerXml.ToString();
            byte[] BUFXML = ASCIIEncoding.UTF8.GetBytes(XMLxmlDocument);
            MemoryStream ms1 = new MemoryStream(BUFXML);

            XmlSerializer DeserializerPlaces = new XmlSerializer(typeof(Query));//, new XmlRootAttribute("Query"));
            using (XmlReader reader = new XmlTextReader(ms1))
            {
                Query dezerializedXML = (Query)DeserializerPlaces.Deserialize(reader);

                string temp = dezerializedXML.Results.Channel.Item.Condition.Temp;
                string text = dezerializedXML.Results.Channel.Item.Condition.Text;

            }// Put a break-point here, then mouse-over temp and text, you should have you values (dezerializedXML contains the entire object)
        }
        catch (System.Exception)
        {
            throw;
        }

答案 2 :(得分:-1)

我使用xml linq和Regex。我不得不修复你的xml问题。我认为主要问题是命名空间。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                "<Root xmlns:yahoo=\"abc\" xmlns:yweather=\"def\">" +
                "<query yahoo:count=\"1\" yahoo:created=\"2016-03-31T06:43:49Z\">" +
                  "yahoo:lang=\"en-US\"><results>" +
                    "<channel>" +
                      "<item>" +
                        "<yweather:condition>" +
                          "code=\"28\" date=\"Thu, 31 Mar 2016 08:00 AM SAST\" temp=\"58\" text=\"Mostly Cloudy\"/>" +
                        "</yweather:condition>" +
                      "</item>" +
                    "</channel>" +
                  "</results>" +
                "</query>" +
                "</Root>";

            XDocument doc = XDocument.Parse(xml);

            string innertext = doc.Descendants().Where(x => x.Name.LocalName == "condition").Select(y => y.Value).FirstOrDefault();
            string pattern = "\\s?(?'name'[^=]+)=\"(?'value'[^\"]+)\"";
            MatchCollection matches = Regex.Matches(innertext, pattern);
            foreach (Match match in matches)
            {
                Console.WriteLine("Name : {0}, Value : {1}", match.Groups["name"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();
        }
    }
}
相关问题