使用通用标签从XML获取特定数据

时间:2019-06-29 00:58:48

标签: c# xml linq

我发现有关此操作的大多数教程都是基于xml的,而xml实际上具有有用的标签。我正在尝试基于集合中的一个条目来获取一整套记录,并使用具有非常通用标签的XML。

//saved as thisxml.xml in current directory
//note the empty entry in the second row
/*
<?xml version="1.0" encoding="UTF-8"?>
<Note>
    <ROW>
        <ENT>up</ENT>
        <ENT>Medium</ENT>
        <ENT>Red</ENT>
        <ENT>down</ENT>
        <ENT>Medium</ENT>
    </ROW>
    <ROW>
        <ENT>right</ENT>
        <ENT>High</ENT>
        <ENT>Purple</ENT>
        <ENT/>
        <ENT>High</ENT>
    </ROW>
</Note>
*/
using System;
using System.Linq;
using System.Xml.Linq;

namespace ParseGenericXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument document = XDocument.Load("thisxml.xml");
            var selectRow = from r in document.Where(r=>(string)r.Element("ENT").Value=="Purple")
            select new
            {
                value1 = r.Element("ENT").Value,
                value2 = r.Element("ENT").Value,
                value3 = r.Element("ENT").Value,
                value4 = r.Element("ENT").Value,
                value5 = r.Element("ENT").Value
            };

            //selectRow results should be {"right","High","Purple",null,"High"}                   
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

IEnumerable<CitizenDTO> dto = citizens.Select(x => x.ToDTO());