简体   繁体   中英

C# Getting values from xml file

I am trying to get both latitude(lat) and longitude(lon) values from xml file.

The XML file is generated throw Web-request using the below code.

Code

var request = WebRequest.Create("#") as HttpWebRequest;
request.Credentials = new System.Net.NetworkCredential("#", "#");
var response = request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var result = readStream.ReadToEnd();
String xmlString = result;
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(new System.IO.StringReader(xmlString));
reader.Read();
System.Data.DataSet ds = new System.Data.DataSet();
ds.ReadXml(reader, System.Data.XmlReadMode.Auto);
DataTable dt = ds.Tables[0];
lbllat.Text = dt.Rows[0][5].ToString();//for example 
lbllong.Text = dt.Rows[0][6].ToString();

But the code gives this following error msg.

Error: '>' is an unexpected token. The expected token is '='. Line 2, position 483

Mainly The error occurred because XML tags do not accept spaces on.

Generated xml file format.

<?xml version="1.0"?>
<root>
  <code>0</code>
  <msg>OK</msg>
  <data>
    <agentid>1</agentid>
    <imei>3224</imei>
    <typeid>2</typeid>
    <type>Truck</type>
    <vehiclenumber>12121</vehiclenumber>
    <folder>folder1</folder>
    <created_time>1493813160</created_time>
    <current_mileage>4232</current_mileage>
    <status>
      <active>1</active>
      <speed>0</speed>
      <direction>303</direction>
      <lat>3.79092</lat>
      <lon>69.51279</lon>
      <alt>1</alt>
      <satsinview>18</satsinview>
      <unixtimestamp>1503389638</unixtimestamp>
      <sensors>
        <Ignition sensor="">Off</Ignition sensor><External power="" supply="">On</External power supply>
      </sensors>
    </status>
  </data>
</root>

any suggestions ?

First, get the XML fixed, but if you can't then use HTML Agility Pack to retrieve the mal-formed XML. It's pretty good for webscraping, and dealing with badly formed XML.

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