导入具有非典型格式的XML到一个类中

huangapple go评论70阅读模式
英文:

Import XML with a non typical format to a class

问题

我需要导入一个看起来像这样的XML文件:

    <Carpark>
       <Trucks>
          <Truck brand='Chrysler' kg='2100'/>
       </Trucks>
       <Cars>
          <Car brand='Mercedes' kg='1100'/>
       </Cars>
       <Tractors>
          <Tractor brand='John Deere' kg='1500'/>
       </Tractors>
    </Carpark>

基本上,我想要有一个这样的Carpark列表:

    public class Carpark
    {
        // Type can be for example Truck, Car
        public string Type { get; set; }
        public string Brand { get; set; }
        public int Weight { get; set; }
    }

我不明白如何将这个XML文件转换成我想要的类。

我尝试过:

    XElement xElement = XElement.Load(filePath);
    IEnumerable<Carpark> carpark = xElement.Elements();

    foreach(var vehicle in carpark)
    {
        // 一旦我写出这行,我对接下来该怎么做感到困惑
        Console.WriteLine(vehicle.ToString());
    }
英文:

I need to import a XML file looking like this:

<Carpark>
   <Trucks>
      <Truck brand='Chrysler' kg='2100'/>
   </Trucks>
   <Cars>
      <Car brand='Mercedes' kg='1100'/>
   </Cars>
   <Tractors>
      <Tractor brand='John Deere' kg='1500'/>
   </Tractors>
</Carpark>

Essentially I want to have a list of Carpark like this:

public class Carpark
{
    // Type can be for example Truck, Car
    public string Type { get; set; }
    public string Brand { get; set; }
    public int Weight { get; set; }
}

I don't understand how to convert this XML file to the class I want.

What I have tried is:

XElement xElement = XElement.Load(filePath);
IEnumerable<Carpark> carpark = xElement.Elements();

foreach(var vehicle in carpark)
{
    // Once I wrote out the line I was confused as to how to proceed
    Console.WriteLine(vehicle.ToString());
}

答案1

得分: 1

以下是您要翻译的内容:

使用Linq_To_XML和我相信还可以使用NewtonsoftJSON来完成这个操作:

void Main()
{
    var xml = XElement.Parse(x)
        .DescendantsAndSelf("Carpark")
        .Descendants()
        .Where(xe => xe.HasAttributes)
        .Select(xe => new Carpark {
            Type = xe.Name.ToString(),
            Brand = (string)xe.Attribute("brand"),
            Weight = (int)xe.Attribute("kg")
        });

    foreach (var cp in xml)
    {
        Console.WriteLine($"{cp.Type}, {cp.Brand}, {cp.Weight}");
    }
}

static readonly string x = @"<Carpark>
   <Trucks>
      <Truck brand='Chrysler' kg='2100'/>
   </Trucks>
   <Cars>
      <Car brand='Mercedes' kg='1100'/>
   </Cars>
   <Tractors>
      <Tractor brand='John Deere' kg='1500'/>
   </Tractors>
</Carpark>";

public class Carpark
{
    // Type can be for example Truck, Car
    public string Type { get; set; }
    public string Brand { get; set; }
    public int Weight { get; set; }
}
英文:

You can do that with Linq_To_XML and I believe with NewtonsoftJSON:

void Main()
{
	var xml = XElement.Parse(x)
		.DescendantsAndSelf(&quot;Carpark&quot;)
		.Descendants()
		.Where(xe =&gt; xe.HasAttributes)
		.Select(xe =&gt; new Carpark {
			Type = xe.Name.ToString(),
			Brand = (string)xe.Attribute(&quot;brand&quot;),
			Weight = (int)xe.Attribute(&quot;kg&quot;)
		})
		;
		
	foreach (var cp in xml)
	{
		Console.WriteLine($&quot;{cp.Type}, {cp.Brand}, {cp.Weight}&quot;);
	}
	
}

static readonly string x = @&quot;&lt;Carpark&gt;
   &lt;Trucks&gt;
      &lt;Truck brand=&#39;Chrysler&#39; kg=&#39;2100&#39;/&gt;
   &lt;/Trucks&gt;
   &lt;Cars&gt;
      &lt;Car brand=&#39;Mercedes&#39; kg=&#39;1100&#39;/&gt;
   &lt;/Cars&gt;
   &lt;Tractors&gt;
      &lt;Tractor brand=&#39;John Deere&#39; kg=&#39;1500&#39;/&gt;
   &lt;/Tractors&gt;
&lt;/Carpark&gt;&quot;;

public class Carpark
{
	// Type can be for example Truck, Car
	public string Type { get; set; }
	public string Brand { get; set; }
	public int Weight { get; set; }
}

答案2

得分: 0

你可以使用以下类来自动使用 XmlSerializer 进行反序列化:

public class Carpark
{
    public List<Truck> Trucks { get; set; }
    public List<Car> Cars { get; set; }
    public List<Tractor> Tractors { get; set; }
}

[XmlInclude(typeof(Truck))]
[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Tractor))]
public class Vehicle
{
    [XmlIgnore]
    public string Type => this.GetType().Name;

    [XmlAttribute("brand")]
    public string Brand { get; set; }

    [XmlAttribute("kg")]
    public int Weight { get; set; }
}

public class Truck : Vehicle
{
}

public class Car : Vehicle
{
}

public class Tractor : Vehicle
{
}

然后,你可以使用以下代码来进行反序列化:

var cp = (Carpark)serializer.Deserialize(someStreamReader);

如果需要更多帮助,请告诉我。

英文:

You can use the following classes to deserialize this with XmlSerializer automatically

public class Carpark
{
	public List&lt;Truck&gt; Trucks { get; set; }
	public List&lt;Car&gt; Cars { get; set; }
	public List&lt;Tractor&gt; Tractors { get; set; }
}

[XmlInclude(typeof(Truck))]
[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Tractor))]
public class Vehicle
{
	[XmlIgnore]
	public string Type =&gt; this.GetType().Name;
	
	[XmlAttribute(&quot;brand&quot;)]
	public string Brand { get; set; }
	
	[XmlAttribute(&quot;kg&quot;)]
	public int Weight { get; set; }
}

public class Truck : Vehicle
{
}

public class Car : Vehicle
{
}

public class Tractor : Vehicle
{
}

var cp = (Carpark)serializer.Deserialize(someStreamReader);

dotnetfiddle

huangapple
  • 本文由 发表于 2023年6月22日 00:46:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定