简单的XML解析 [英] simple xml parsing

查看:166
本文介绍了简单的XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是解析lat和长出来下​​面的XML片段的最简单的方法。没有命名空间等。

这是一个字符串变量。不是甲流。

 < POI>
      <城市>斯德哥尔摩< /城市>
      <国家>瑞典< /国家>
      < gpoint>
        <纬度> 51.1< /纬度>
        < LNG> 67.98< / LNG>
      < / gpoint>
< / POI>
 

一切我已阅读到目前为止waaaaay什么应该是一个简单的任务太复杂 例如 <一href="http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx">http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx

我一直在看上面的链接

当然,还有一个更简单的方法来做到这一点。NET?

解决方案

 使用System.IO;
使用的System.Xml;
使用System.Xml.XPath;
 

。 。

  XML字符串= @&LT; POI&GT;
                     &LT;城市&GT;斯德哥尔摩&LT; /城市&GT;
                     &LT;国家&GT;瑞典&LT; / COUNTR&GT;
                        &LT; gpoint&GT;
                            &LT;纬度&GT; 51.1&LT; /纬度&GT;
                            &LT; LNG&GT; 67.98&LT; / LNG&GT;
                        &LT; / gpoint&GT;
                   &所述; / POI&gt;中;

    XmlReaderSettings设置=新XmlReaderSettings();
    set.ConformanceLevel = ConformanceLevel.Fragment;

    XPathDocument中DOC =
        新的XPathDocument(XmlReader.Create(新StringReader(XML),置));

    XPathNavigator的NAV = doc.CreateNavigator();


    Console.WriteLine(nav.SelectSingleNode(/ POI / gpoint /纬度));
    Console.WriteLine(nav.SelectSingleNode(/ POI / gpoint / LNG));
 

您当然可以使用XPath的的SelectSingleNode 选择&LT; gpoint&GT; 元素到一个变量

what is the simplest way to parse the lat and long out of the following xml fragment. There is no namespace etc.

It is in a string variable. not a stream.

<poi>
      <city>stockholm</city>
      <country>sweden</country>
      <gpoint>
        <lat>51.1</lat>
        <lng>67.98</lng>
      </gpoint>
</poi>

everything I have read so far is waaaaay too complex for what should be a simple task e.g. http://geekswithblogs.net/kobush/archive/2006/04/20/75717.aspx

I've been looking at the above link

Surely there is a simpler way to do this in .net?

解决方案

using System.IO;
using System.Xml;
using System.Xml.XPath;

. . .

    string xml = @"<poi>      
                     <city>stockholm</city>  
                     <country>sweden</countr>
                        <gpoint>        
                            <lat>51.1</lat>        
                            <lng>67.98</lng>    
                        </gpoint>
                   </poi>";

    XmlReaderSettings set = new XmlReaderSettings();
    set.ConformanceLevel = ConformanceLevel.Fragment;

    XPathDocument doc = 
        new XPathDocument(XmlReader.Create(new StringReader(xml), set));

    XPathNavigator nav = doc.CreateNavigator();


    Console.WriteLine(nav.SelectSingleNode("/poi/gpoint/lat"));
    Console.WriteLine(nav.SelectSingleNode("/poi/gpoint/lng"));

You could of course use xpath SelectSingleNode to select the <gpoint> element into a variable.

这篇关于简单的XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆