C# 如何从xml中读取数据?

C# 如何从xml中读取数据?,c#,xml,web,xmlnode,C#,Xml,Web,Xmlnode,我正在使用一个返回以下xml的web服务。 在c#中,我建立了连接并返回一个XmlNode类型的对象 我需要提取这些值​​主要时间段=“2010”OBS值=“4796580” 如果你能帮助我,我将不胜感激 这是XML <CompactData xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message" xmlns:inegi="urn:sdmx:org.sdmx.infomodel.keyfamily.KeyFamil

我正在使用一个返回以下xml的web服务。 在c#中,我建立了连接并返回一个XmlNode类型的对象

我需要提取这些值​​主要时间段=“2010”OBS值=“4796580” 如果你能帮助我,我将不胜感激

这是XML

<CompactData xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message" xmlns:inegi="urn:sdmx:org.sdmx.infomodel.keyfamily.KeyFamily=inegi:TIPO_B_DSD:compact" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message SDMXMessage.xsd urn:estat:sdmx.infomodel.keyfamily.KeyFamily=inegi:DSD_TIPO_B:1.0:compact inegi:DSD_TIPO_B_Compact.xsd">
<Header>
<ID>BISE</ID>
<Prepared>2016-05-10T20:00:51</Prepared>
<Sender id="INEGI">
<Name xml:lang="en">Instituto Nacional de Estadística y Geografía</Name>
<Contact>
<Name xml:lang="en">Atención a usuarios</Name>
<Email>
http://www.inegi.org.mx/inegi/contacto/default.aspx
</Email>
</Contact>
</Sender>
</Header>
<inegi:DataSet>
<inegi:Series INDICADOR="1002000001" COBER_GEO="07000 " FREQ="V" DECIMALS="0" TOPIC="000400010001" NOTE="9,49,115,422,425">
<inegi:Obs TIME_PERIOD="2010" OBS_VALUE="4796580" OBS_STATUS="D" OBS_UNIT="Número de personas" OBS_SOURCE="487" OBS_NOTE="115,425"/>
</inegi:Series>
</inegi:DataSet>
</CompactData>

野牛
2016-05-10T20:00:51
国家科学和地理研究所
阿坦西翁
http://www.inegi.org.mx/inegi/contacto/default.aspx
使用此代码

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);
XmlNode dataNode = doc.SelectSingleNode("/*[local-name()='CompactData']/*[local-name()='DataSet']/*[local-name()='Series']/*[local-name()='Obs']");
String obsValue = dataNode.Attributes ["OBS_VALUE"];
String timePeriod = dataNode.Attributes["TIME_PERIOD"];

最好的方法是忽略名称空间并使用下面的代码

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement obs = doc.Descendants().Where(x => x.Name.LocalName == "Obs").FirstOrDefault();

            string TIME_PERIOD = obs.Attribute("TIME_PERIOD").Value;
            string OBS_VALUE = obs.Attribute("OBS_VALUE").Value;
        }
    }
}