簡體   English   中英

獲取 xml 節點的文本

[英]Get text for xml node

示例 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);
}

我一直在努力輸出臨時文本,但我找不到方法,這是我得到的。

您可以從XmlNode.Attributes屬性訪問 XML 屬性:

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

嘗試這個....

使用....

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;
        }

我將 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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM