如何从xml读取数据?

时间:2016-05-11 01:16:53

标签: c# xml web xmlnode

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

我需要提取这些值主要是TIME_PERIOD =“2010”OBS_VALUE =“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>

2 个答案:

答案 0 :(得分:1)

使用此代码。

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"];

答案 1 :(得分:0)

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

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