使用LINQ和高度嵌套的XML创建类对象

本文关键字:XML 创建 对象 嵌套 LINQ 高度 使用 | 更新日期: 2023-09-27 17:54:01

我有需要加载和创建类对象的xml文件,但是,这些文件的格式在我看来是一种可笑的嵌套方式。遗憾的是,我不能重新格式化xml文件。下面是它们的样子(假设每个客户只有一个购买条目,并且名称可以用作键):

<root>
<start>
   <customer>
      <store store = "a">
          <customer name = "Ted Johnson">
             <product product = "shampoo">
                <price price = "10">
                </ price>
             </ product>
          </customer>
       </store>
       <store store = "b">
           <customer name = "Janet Henry">
             <product product = "soda">
                <price price = "2">
                </ price>
             </ product>
          </ customer>
       </ store>
   </ customer>
   <tax>
      <store store = "a">
          <customer name = "Ted Johnson">
             <product product = "shampoo">
                <tax tax = "1">
                  <date date = "4/4/2014">
                  </date>
                </tax>
             </ product>
          </customer>
       </store>         
      <store store = "b">
          <customer name = "Janet Henry">
             <product product = "soda">
                <tax tax = "0.2">
                  <date date = "5/5/2014">
                  </date>
                </tax>
             </ product>
          </customer>
       </store>
   </tax>
</ start>
</ root>

现在我需要在c#/WPF中创建基于这种怪物的类对象。我已经尝试了一些方法,但一直遇到障碍,我担心我可能最终会花费很长时间来强制执行低效的解决方案。有什么简单的方法可以解决这个问题吗?

我的目标是创建如下内容:

var customerPurchases = (from e in xml.Descendants(ns + "start")                         
   select new customerPurchase
   {
     name = e.Attribute("name").Value,
     store = e.Attribute("store").Value,
     product = e.Attribute("product").Value,
     price = e.Attribute("price").Value,
     tax = e.Attribute("tax").Value,
     date = e.Attribute("date").Value,  
}).ToList();

任何帮助或见解在这个混乱将非常感激!

使用LINQ和高度嵌套的XML创建类对象

您可以将XML字符串(或文件)反序列化为c#对象。在这里找到一个示例:https://blog.udemy.com/csharp-serialize-to-xml/

首先,必须有与XML相关联的类。要创建类,请选择您的XML样本数据,然后在Visual Studio中转到编辑/粘贴特殊/将XML粘贴为类。

接下来,使用下面的示例:

        String xData = System.IO.File.ReadAllText(@"C:'Temp'MyFile.xml");
        XmlSerializer x = new XmlSerializer(typeof(root));
        root dataConverted = (root)x.Deserialize(new StringReader(xData));
        // root object contains all XML data.

如果您不太担心速度,我会使用LINQ to XML。

我会尝试将XML转换为动态c#对象。然后,将数据从动态对象读入强类型POCO类的代码将更加简洁,也更容易编写。

参见将XML转换为动态c#对象。

提示:如果你将整个解析器包装在try/catch中,那么XML输入的模式和使用动态的解析代码之间的任何不匹配都将被检测出来,而不会导致整个应用程序崩溃。