将Model Property映射到外部节点XML属性

时间:2018-04-07 08:40:05

标签: c# xml

是否可以将models属性映射到使用XmlAttribute和XPath?

例如我有这个XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<export>
  <patients>
    <pbt>
      <id>521</id>
      <prt_id>521</prt_id> <!-- I need to grab this and store it in a Panel model -->
    </pbt>
  </patients>
  <results>
    <panel> <!-- I am parsing the XML for panels -->
      <type>Foo</type>
      <pbt_id>521</pbt_id>
    </panel>
  </results>
</export>

我正在将XML解析为此模型:

class Panel
{
    [XmlElement("type")]
    public string Type { get; set; }

    [XmlElement("pbt_id")]
    public string PbtId { get; set; }

    // Some xml path selector here?
    [XmlElement("/export/patients/prt_id")]
    public string PrtId { get; set; }
}

我可以在装饰器(?)中使用XPath查询吗?如果没有,任何想法如何在我序列化时如何获取外部节点值:

XmlSerializer deserializer = new XmlSerializer(typeof(List<Panel>));
TextReader textReader = new StreamReader(@"C:\Panel.xml");
List<Panel> panels; 
panels = (List<Panel>)deserializer.Deserialize(textReader);

1 个答案:

答案 0 :(得分:1)

解析xml并从不同的分支(级别)获取数据并放入单个类时,最好使用xml linq而不是序列化。见下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication34
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            new Panel(FILENAME);
        }

    }
    public class Panel
    {
        public static Dictionary<string, Panel> panels = new Dictionary<string, Panel>();


        public string Type { get; set; }
        public string PbtId { get; set; }
        public string PrtId { get; set; }

        public Panel() { }
        public Panel(string filename)
        {
            XDocument doc = XDocument.Load(filename);

            panels = doc.Descendants("panel").Select(x => new Panel()
            {
                Type = (string)x.Element("type"),
                PbtId = (string)x.Element("pbt_id")
            }).GroupBy(x => x.PbtId, y => y)
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            foreach (XElement  pbt in doc.Descendants("pbt"))
            {
                string id = (string)pbt.Element("id");
                string prt_id = (string)pbt.Element("prt_id");
                if(panels.ContainsKey(id))
                {
                    panels[id].PrtId = prt_id;
                }

            }
        }
    }
}