简体   繁体   中英

How to read the data or attributes from the xml node “OuterXml”

<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0" >
    </image>
    <suggested_pickup>15 minutes after the hour</suggested_pickup>
    <suggested_pickup_period>60</suggested_pickup_period>
    <temp_f>44.0</temp_f>
    <temp_c>6.7</temp_c>
    <relative_humidity>55</relative_humidity>
    <wind_string>North at 6.9 MPH (6 KT)</wind_string>
    <wind_dir>North</wind_dir>
    <wind_degrees>340</wind_degrees>
    <wind_mph>6.9</wind_mph>
    <wind_kt>6</wind_kt>
    <pressure_string>1025.2 mb</pressure_string>
    <pressure_mb>1025.2</pressure_mb>
    <pressure_in>30.28</pressure_in>
    <dewpoint_string>28.9 F (-1.7 C)</dewpoint_string>
    <dewpoint_f>28.9</dewpoint_f>
    <dewpoint_c>-1.7</dewpoint_c>
</current_observation>

I want to get some attributes lik wind_dir , wind_kt etc from the above xml data. I have tried this:

var dayt = GetXMLAsString(WeatherXML);
XDocument doc = XDocument.Parse(dayt);

var r = from element in doc.Elements()
        where element.Name == "latitude"
        select element;

foreach (var item in r)
{
    Console.WriteLine(item.Value);
}

I want this data to be converted into an array or model to send it to ajax result .

I have tried this earlier but kept ".value":

var a = from hash in doc.Descendants("latitude") select hash.value;

I got proper result when i tried as follows: XmlDocument WeatherXML = new XmlDocument(); WeatherXML.Load(reader);

            var dayt = GetXMLAsString(WeatherXML);
            XDocument doc = XDocument.Parse(dayt);

var a = from hash in doc.Descendants("latitude") select hash;

            var asdd = from hash in doc.Descendants("current_observation")
                    select hash;

With use of System.Xml.Linq namespace we have a set of convenient methods to call. In your case following code can help:

var doc = XDocument.Parse(WeatherXML);
var value = from e in doc.Elements()
            where e.Name == "wind_kt"
            select e.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM