简单的XML解析简单、XML

2023-09-03 13:09:15 作者:恋战 WhiteInte

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

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

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

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

我一直在看上面的链接

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

解决方案

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

。 。

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

    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));
 
简单实现DOM4J解析查询XML

您当然可以使用XPath的的SelectSingleNode 选择< gpoint> 元素到一个变量

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.