首页 > 解决方案 > 在 C sharp 中读取单个 xml 选项卡

问题描述

我正在尝试使用 c sharp 从下面的 xml 文件中读取 Lat、Long 和 Alt 的各个值。xml 的格式与我之前使用的格式不同。我可以从文件中提取元素,但我试图只读取 Lat、Long、Alt 等的单个值。我无法弄清楚如何使用 XmlReader 或 LINQ 来做到这一点。

文件:

<Entry MC="11" Time="0.00" ActName="SCR_ON">
   <ActingPlat ID="1"/>
   <AgainstPos Lat="24.5399" Lon="46.7704" Alt="567"/>
</Entry>

标签: c#xml

解决方案


使用 XML Linq

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

            var results = doc.Descendants("AgainstPos").Select(x => new
            {
                lat = (decimal)x.Attribute("Lat"),
                lon = (decimal)x.Attribute("Lon"),
                alt = (decimal)x.Attribute("Alt")
            }).ToList();
        }
    }
}

推荐阅读