【问题标题】:How to read data from an xml? [duplicate]如何从 xml 中读取数据? [复制]
【发布时间】:2016-05-11 01:16:53
【问题描述】:

我正在使用返回以下 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>

【问题讨论】:

    标签: c# xml web xmlnode


    【解决方案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"];
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多